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(sheet): add basic pasting feature (#164)

Wenzhao Hu68346b436b09
diff --git a/packages/base-render/src/Component/Docs/Document.Editor.ts b/packages/base-render/src/Component/Docs/Document.Editor.ts
index ee98ad7798..ecdddfa2be 100644
--- a/packages/base-render/src/Component/Docs/Document.Editor.ts
+++ b/packages/base-render/src/Component/Docs/Document.Editor.ts
@@ -1,4 +1,5 @@
-import { DataStreamTreeTokenType, Nullable, Observable, Observer } from '@univerjs/core';
+import { DataStreamTreeTokenType, Nullable, Observable, Observer, RxDisposable } from '@univerjs/core';
+import { fromEvent, Observable as RxObservable, share, takeUntil } from 'rxjs';
import { CURSOR_TYPE } from '../../Basics/Const';
import { IDocumentSkeletonCached } from '../../Basics/IDocumentSkeletonCached';
@@ -21,7 +22,7 @@ export interface IEditorInputConfig {
selectionList?: TextSelection[];
}
-export class DocsEditor {
+export class DocsEditor extends RxDisposable {
onKeydownObservable = new Observable<IEditorInputConfig>();
onInputObservable = new Observable<IEditorInputConfig>();
@@ -34,6 +35,8 @@ export class DocsEditor {
onSelectionStartObservable = new Observable<Nullable<INodePosition>>();
+ onPaste$: RxObservable<ClipboardEvent>;
+
private _container: HTMLDivElement;
private _inputParent: HTMLDivElement;
@@ -73,10 +76,10 @@ export class DocsEditor {
private _isIMEInputApply = false;
constructor(private _documents?: DocComponent) {
- this._initialDom();
+ super();
+ this._initDOM();
this.activeViewport = this._documents?.getFirstViewport();
-
if (this._documents) {
this.changeDocuments(this._documents);
}
@@ -211,14 +214,16 @@ export class DocsEditor {
this._attachSelectionEvent(this._documents);
}
- dispose() {
+ override dispose() {
+ super.dispose();
+
if (this._documents) {
this._detachEvent(this._documents);
}
this._container.remove();
}
- private _initialDom() {
+ private _initDOM() {
const container = document.createElement('div');
container.style.position = 'absolute';
container.style.left = `0px`;
@@ -237,16 +242,14 @@ export class DocsEditor {
this._input = inputDom;
this._cursor = cursorDom;
- this._initialInput();
-
- this._initialCursorDom();
-
- this._attachInputEvent();
+ this._initInput();
+ this._initDOMCursor();
+ this._initInputEvents();
document.body.appendChild(container);
}
- private _initialInput() {
+ private _initInput() {
this._inputParent.style.cssText = `
position:absolute;
height:1px;
@@ -270,7 +273,7 @@ export class DocsEditor {
`;
}
- private _initialCursorDom() {
+ private _initDOMCursor() {
this._cursor.style.cssText = `
visibility: visible;
position: absolute;
@@ -594,8 +597,9 @@ export class DocsEditor {
}
// eslint-disable-next-line max-lines-per-function
- private _attachInputEvent() {
- // NOTE@wzhudev: keydown is probably unnecessary
+ private _initInputEvents() {
+ // TODO: emit these paste event
+
this._input.addEventListener('keydown', (e) => {
if (this._isIMEInputApply) {
return;
@@ -704,6 +708,15 @@ export class DocsEditor {
selectionList,
});
});
+
+ this.onPaste$ = (fromEvent(this._input, 'paste') as RxObservable<ClipboardEvent>).pipe(
+ takeUntil(this.dispose$),
+ share()
+ );
+ }
+
+ private _handlePaste(e: ClipboardEvent) {
+ // TODO: emit the paste event to subscribers
}
// eslint-disable-next-line max-lines-per-function
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index 619acce93c..2b5d8157c5 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -16,7 +16,7 @@ import { SetSelectionsOperation } from './commands/operations/selection.operatio
import { BasicWorkbookController, CountBarController } from './Controller';
import { BasicWorksheetController } from './Controller/BasicWorksheet.controller';
import { FormulaBarController } from './Controller/FormulaBarController';
-import { SelectionController } from './Controller/selection.controller';
+import { SelectionController } from './Controller/Selection.controller';
import { SheetRenderController } from './Controller/sheet-render.controller';
import { en } from './Locale';
import { BorderStyleManagerService } from './services/border-style-manager.service';
diff --git a/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts b/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts
index 29f4dd0a5c..a068d49d15 100644
--- a/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts
@@ -8,6 +8,8 @@ import {
IRemoveRowMutationParams,
} from '../../Basics/Interfaces/MutationInterface';
+// TODO: InsertRowMutation should have an undo factory
+
export const InsertRowMutationFactory = (
accessor: IAccessor,
params: IInsertRowMutationParams
diff --git a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
index 527c3b0b13..6ecf38b813 100644
--- a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -13,11 +13,15 @@ import { IAccessor } from '@wendellhu/redi';
/** Params of `SetRangeValuesMutation` */
export interface ISetRangeValuesMutationParams {
- rangeData: ISelectionRange[];
+ workbookId?: string;
worksheetId: string;
+ rangeData: ISelectionRange[];
cellValue?: ObjectMatrixPrimitiveType<ICellData>;
- workbookId?: string;
+
+ /**
+ * @deprecated not a good design
+ */
options?: ICopyToOptionsData;
}
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 4c42d6c72b..0efeb85e7a 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -22,6 +22,16 @@ export {
export { InsertSheetMutation, InsertSheetUndoMutationFactory } from './commands/mutations/insert-sheet.mutation';
export { RemoveSheetMutation, RemoveSheetUndoMutationFactory } from './commands/mutations/remove-sheet.mutation';
export { ISetRangeStyleMutationParams, SetRangeStyleMutation } from './commands/mutations/set-range-styles.mutation';
+export { ISetRangeValuesMutationParams, SetRangeValuesMutation } from './commands/mutations/set-range-values.mutation';
+export { SetTabColorMutation } from './commands/mutations/set-tab-color.mutation';
+export { SetWorksheetActivateMutation } from './commands/mutations/set-worksheet-activate.mutation';
+export {
+ SetWorksheetColWidthMutation,
+ SetWorksheetColWidthMutationFactory,
+} from './commands/mutations/set-worksheet-col-width.mutation';
+export { SetWorksheetHideMutation } from './commands/mutations/set-worksheet-hide.mutation';
+export { SetWorksheetNameMutation } from './commands/mutations/set-worksheet-name.mutation';
+export { SetWorksheetOrderMutation } from './commands/mutations/set-worksheet-order.mutation';
// operations
export { SetSelectionsOperation } from './commands/operations/selection.operation';
@@ -97,9 +107,4 @@ export { SetWorksheetNameCommand } from './commands/commands/set-worksheet-name.
export { SetWorksheetRowHideCommand } from './commands/commands/set-worksheet-row-hide.command';
export { SetWorksheetRowShowCommand } from './commands/commands/set-worksheet-row-show.command';
export { SetWorksheetShowCommand } from './commands/commands/set-worksheet-show.command';
-export { SetTabColorMutation } from './commands/mutations/set-tab-color.mutation';
-export { SetWorksheetActivateMutation } from './commands/mutations/set-worksheet-activate.mutation';
-export { SetWorksheetHideMutation } from './commands/mutations/set-worksheet-hide.mutation';
-export { SetWorksheetNameMutation } from './commands/mutations/set-worksheet-name.mutation';
-export { SetWorksheetOrderMutation } from './commands/mutations/set-worksheet-order.mutation';
export * from './Locale';
diff --git a/packages/base-ui/src/base-ui-plugin.ts b/packages/base-ui/src/base-ui-plugin.ts
index 27aa5d1e90..fde2210d46 100644
--- a/packages/base-ui/src/base-ui-plugin.ts
+++ b/packages/base-ui/src/base-ui-plugin.ts
@@ -10,6 +10,10 @@ import { DesktopClipboardService, IClipboardService } from './services/clipboard
import { BrowserClipboardService, IClipboardInterfaceService } from './services/clipboard/clipboard-interface.service';
import { DesktopContextMenuService, IContextMenuService } from './services/contextmenu/contextmenu.service';
import { DesktopMenuService, IMenuService } from './services/menu/menu.service';
+import { DesktopMessageService } from './services/message/desktop-message.service';
+import { IMessageService } from './services/message/message.service';
+import { DesktopNotificationService } from './services/notification/desktop-notification.service';
+import { INotificationService } from './services/notification/notification.service';
import { DesktopPlatformService, IPlatformService } from './services/platform/platform.service';
import { DesktopShortcutService, IShortcutService } from './services/shortcut/shortcut.service';
@@ -54,6 +58,8 @@ export class UIPlugin extends Plugin {
[IContextMenuService, { useClass: DesktopContextMenuService }],
[IClipboardInterfaceService, { useClass: BrowserClipboardService }],
[IClipboardService, { useClass: DesktopClipboardService }],
+ [INotificationService, { useClass: DesktopNotificationService }],
+ [IMessageService, { useClass: DesktopMessageService }],
// controllers
[SharedController],
diff --git a/packages/base-ui/src/index.ts b/packages/base-ui/src/index.ts
index 1dea415d27..703cbe890b 100644
--- a/packages/base-ui/src/index.ts
+++ b/packages/base-ui/src/index.ts
@@ -12,7 +12,12 @@ export * from './Locale';
export { CopyCommand, CutCommand, PasteCommand } from './services/clipboard/clipboard.command';
export { DesktopClipboardService, IClipboardService } from './services/clipboard/clipboard.service';
export { CopyShortcutItem, CutShortcutItem, PasteShortcutItem } from './services/clipboard/clipboard.shortcut';
-export { BrowserClipboardService, IClipboardInterfaceService } from './services/clipboard/clipboard-interface.service';
+export {
+ BrowserClipboardService,
+ HTML_CLIPBOARD_MIME_TYPE,
+ IClipboardInterfaceService,
+ PLAIN_TEXT_CLIPBOARD_MIME_TYPE,
+} from './services/clipboard/clipboard-interface.service';
export {
ICustomComponentOption,
ICustomComponentProps,
@@ -28,6 +33,10 @@ export {
MenuPosition,
} from './services/menu/menu';
export { DesktopMenuService, IMenuService } from './services/menu/menu.service';
+export { DesktopMessageService } from './services/message/desktop-message.service';
+export { IMessageService } from './services/message/message.service';
+export { DesktopNotificationService } from './services/notification/desktop-notification.service';
+export { INotificationService } from './services/notification/notification.service';
export { DesktopPlatformService, IPlatformService } from './services/platform/platform.service';
export { KeyCode, MetaKeys } from './services/shortcut/keycode';
export { DesktopShortcutService, IShortcutItem, IShortcutService } from './services/shortcut/shortcut.service';
diff --git a/packages/base-ui/src/services/clipboard/clipboard-interface.service.ts b/packages/base-ui/src/services/clipboard/clipboard-interface.service.ts
index 4349835ad8..80cec77ceb 100644
--- a/packages/base-ui/src/services/clipboard/clipboard-interface.service.ts
+++ b/packages/base-ui/src/services/clipboard/clipboard-interface.service.ts
@@ -1,6 +1,9 @@
import { Disposable } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
+export const PLAIN_TEXT_CLIPBOARD_MIME_TYPE = 'text/plain';
+export const HTML_CLIPBOARD_MIME_TYPE = 'text/html';
+
/**
* This interface provides an interface to access system's clipboard.
*/
@@ -10,13 +13,6 @@ export interface IClipboardInterfaceService {
* @param text
*/
writeText(text: string): Promise<void>;
-
- /**
- * Read plain text from clipboard. Use read() to read both plain text and html.
- * @returns plain text
- */
- readText(): Promise<string>;
-
/**
* Write both plain text and html into clipboard.
* @param text
@@ -25,9 +21,14 @@ export interface IClipboardInterfaceService {
write(text: string, html: string): Promise<void>;
/**
- * Read both plain text and html from clipboard.
+ * Read plain text from clipboard. Use read() to read both plain text and html.
+ * @returns plain text
*/
- read(): Promise<{ text: string; html: string }>;
+ readText(): Promise<string>;
+ /**
+ * Read `ClipboardItem[]` from clipboard.
+ */
+ read(): Promise<ClipboardItem[]>;
// NOTE: maybe we should add an interface to support image copy
}
@@ -42,7 +43,8 @@ export class BrowserClipboardService extends Disposable implements IClipboardInt
// write both pure text content and html content to the clipboard
return await navigator.clipboard.write([
new ClipboardItem({
- 'text/html': new Blob([html], { type: 'text/html' }),
+ [PLAIN_TEXT_CLIPBOARD_MIME_TYPE]: new Blob([text], { type: PLAIN_TEXT_CLIPBOARD_MIME_TYPE }),
+ [HTML_CLIPBOARD_MIME_TYPE]: new Blob([html], { type: HTML_CLIPBOARD_MIME_TYPE }),
}),
]);
} catch (error) {
@@ -75,7 +77,9 @@ export class BrowserClipboardService extends Disposable implements IClipboardInt
document.removeChild(container);
}
- read(): Promise<{ text: string; html: string }> {}
+ async read(): Promise<ClipboardItem[]> {
+ return navigator.clipboard.read();
+ }
async readText(): Promise<string> {
try {
@@ -85,8 +89,6 @@ export class BrowserClipboardService extends Disposable implements IClipboardInt
return '';
}
-
- // TODO: fallback to traditional way
}
}
diff --git a/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts b/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts
index 7b898b1719..1ef4951e96 100644
--- a/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts
+++ b/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts
@@ -1,6 +1,6 @@
import { KeyCode, MetaKeys } from '../shortcut/keycode';
import { IShortcutItem } from '../shortcut/shortcut.service';
-import { CopyCommand, CutCommand } from './clipboard.command';
+import { CopyCommand, CutCommand, PasteCommand } from './clipboard.command';
export const CopyShortcutItem: IShortcutItem = {
id: CopyCommand.id,
@@ -13,6 +13,6 @@ export const CutShortcutItem: IShortcutItem = {
};
export const PasteShortcutItem: IShortcutItem = {
- id: CopyCommand.id,
+ id: PasteCommand.id,
binding: KeyCode.V | MetaKeys.CTRL_COMMAND,
};
diff --git a/packages/base-ui/src/services/contextmenu/contextmenu.service.ts b/packages/base-ui/src/services/contextmenu/contextmenu.service.ts
index 0f0f5b245f..b367795cb4 100644
--- a/packages/base-ui/src/services/contextmenu/contextmenu.service.ts
+++ b/packages/base-ui/src/services/contextmenu/contextmenu.service.ts
@@ -12,6 +12,8 @@ export interface IContextMenuService {
export const IContextMenuService = createIdentifier<IContextMenuService>('univer.context-menu-service');
+// TODO: support context menu in cell editor?
+
export class DesktopContextMenuService extends Disposable implements IContextMenuService {
private _currentHandler: IContextMenuHandler | null = null;
diff --git a/packages/base-ui/src/services/message/desktop-message.service.ts b/packages/base-ui/src/services/message/desktop-message.service.ts
new file mode 100644
index 0000000000..919214ee5b
--- /dev/null
+++ b/packages/base-ui/src/services/message/desktop-message.service.ts
@@ -0,0 +1,10 @@
+import { toDisposable } from '@univerjs/core';
+import { IDisposable } from '@wendellhu/redi';
+
+import { IMessageService } from './message.service';
+
+export class DesktopMessageService implements IMessageService {
+ show(): IDisposable {
+ return toDisposable(() => {});
+ }
+}
diff --git a/packages/base-ui/src/services/message/message.service.ts b/packages/base-ui/src/services/message/message.service.ts
new file mode 100644
index 0000000000..32d13598a8
--- /dev/null
+++ b/packages/base-ui/src/services/message/message.service.ts
@@ -0,0 +1,7 @@
+import { createIdentifier, IDisposable } from '@wendellhu/redi';
+
+export const IMessageService = createIdentifier<IMessageService>('univer.message-service');
+
+export interface IMessageService {
+ show(): IDisposable;
+}
diff --git a/packages/base-ui/src/services/notification/desktop-notification.service.ts b/packages/base-ui/src/services/notification/desktop-notification.service.ts
new file mode 100644
index 0000000000..bda2404509
--- /dev/null
+++ b/packages/base-ui/src/services/notification/desktop-notification.service.ts
@@ -0,0 +1,10 @@
+import { toDisposable } from '@univerjs/core';
+import { IDisposable } from '@wendellhu/redi';
+
+import { INotificationService } from './notification.service';
+
+export class DesktopNotificationService implements INotificationService {
+ show(): IDisposable {
+ return toDisposable(() => {});
+ }
+}
diff --git a/packages/base-ui/src/services/notification/notification.service.ts b/packages/base-ui/src/services/notification/notification.service.ts
new file mode 100644
index 0000000000..2a5c89770b
--- /dev/null
+++ b/packages/base-ui/src/services/notification/notification.service.ts
@@ -0,0 +1,7 @@
+import { createIdentifier, IDisposable } from '@wendellhu/redi';
+
+export const INotificationService = createIdentifier<INotificationService>('univer.notification-service');
+
+export interface INotificationService {
+ show(): IDisposable;
+}
diff --git a/packages/base-ui/src/services/shortcut/shortcut.service.ts b/packages/base-ui/src/services/shortcut/shortcut.service.ts
index affcc57854..f6f661a195 100644
--- a/packages/base-ui/src/services/shortcut/shortcut.service.ts
+++ b/packages/base-ui/src/services/shortcut/shortcut.service.ts
@@ -82,9 +82,13 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
const macCtrl = binding & MetaKeys.MAC_CTRL;
if (this._platformService.isMac) {
- return `${ctrlKey ? '⌘' : ''}${shiftKey ? '⇧' : ''}${altKey ? '⌥' : ''}${macCtrl ? '⌃' : ''}${String.fromCharCode(binding & 0xff)}`;
+ return `${ctrlKey ? '⌘' : ''}${shiftKey ? '⇧' : ''}${altKey ? '⌥' : ''}${
+ macCtrl ? '⌃' : ''
+ }${String.fromCharCode(binding & 0xff)}`;
}
- return `${ctrlKey ? 'Ctrl+' : ''}${shiftKey ? 'Shift+' : ''}${altKey ? 'Alt+' : ''}${String.fromCharCode(binding & 0xff)}`;
+ return `${ctrlKey ? 'Ctrl+' : ''}${shiftKey ? 'Shift+' : ''}${altKey ? 'Alt+' : ''}${String.fromCharCode(
+ binding & 0xff
+ )}`;
}
private resolveMouseEvent(e: KeyboardEvent): void {
@@ -107,7 +111,12 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
const shouldTrigger = Array.from(shortcuts)
.sort((s1, s2) => (s1.priority ?? 0) - (s2.priority ?? 0))
- .find((s) => s.preconditions?.({ getContextValue: this._contextService.getContextValue.bind(this._contextService) }) ?? true);
+ .find(
+ (s) =>
+ s.preconditions?.({
+ getContextValue: this._contextService.getContextValue.bind(this._contextService),
+ }) ?? true
+ );
if (shouldTrigger) {
this._commandService.executeCommand(shouldTrigger.id, shouldTrigger.staticParameters);
return true;
diff --git a/packages/core/src/Basics/Univer.ts b/packages/core/src/Basics/Univer.ts
index 410e0b16b5..dd1852e26b 100644
--- a/packages/core/src/Basics/Univer.ts
+++ b/packages/core/src/Basics/Univer.ts
@@ -3,6 +3,7 @@ import { Ctor, Injector } from '@wendellhu/redi';
import { ObserverManager } from '../Observer';
import { Plugin, PluginCtor, PluginRegistry, PluginStore, PluginType } from '../plugin/plugin';
import { CommandService, ICommandService } from '../services/command/command.service';
+import { ConfigService, IConfigService } from '../services/config/config.service';
import { ContextService, IContextService } from '../services/context/context.service';
import { CurrentUniverService, ICurrentUniverService } from '../services/current.service';
import { LifecycleStages } from '../services/lifecycle/lifecycle';
@@ -156,6 +157,7 @@ export class Univer {
[ICommandService, { useClass: CommandService, lazy: true }],
[IUndoRedoService, { useClass: LocalUndoRedoService, lazy: true }],
[IPermissionService, { useClass: DesktopPermissionService }],
+ [IConfigService, { useClass: ConfigService }],
[IContextService, { useClass: ContextService }],
]);
}
diff --git a/packages/core/src/Observer/Observable.ts b/packages/core/src/Observer/Observable.ts
index f7a8d155cd..e56c79e5ec 100644
--- a/packages/core/src/Observer/Observable.ts
+++ b/packages/core/src/Observer/Observable.ts
@@ -51,6 +51,8 @@ interface INotifyObserversReturn {
/**
* Represent an WorkBookObserver registered to a given Observable object.
+ *
+ * @deprecated use rxjs instead
*/
export class Observer<T = void> {
/** @hidden */
@@ -76,6 +78,8 @@ export class Observer<T = void> {
/**
* The Observable class is a simple implementation of the Observable pattern.
*
+ * @deprecated use rxjs instead. It is not necessary to create another reactive programming system. Leverage the community.
+ *
* @remarks
* There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
* This enable a more fine grained execution without having to rely on multiple different Observable objects.
@@ -115,7 +119,11 @@ export class Observable<T> {
* @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
* @returns the new observer created for the callback
*/
- add(callback: (eventData: T, eventState: EventState) => void, insertFirst = false, unregisterOnFirstCall = false): Nullable<Observer<T>> {
+ add(
+ callback: (eventData: T, eventState: EventState) => void,
+ insertFirst = false,
+ unregisterOnFirstCall = false
+ ): Nullable<Observer<T>> {
if (!callback) {
return null;
}
diff --git a/packages/core/src/Shared/ObjectArray.ts b/packages/core/src/Shared/ObjectArray.ts
index 2a946eb034..d4819c2959 100644
--- a/packages/core/src/Shared/ObjectArray.ts
+++ b/packages/core/src/Shared/ObjectArray.ts
@@ -48,6 +48,7 @@ const likeArr = (value: object): number => {
/**
* Arrays in object form and provide an array-like API
*
+ * @deprecated this class is badly designed
* @beta
*/
export class ObjectArray<T> {
diff --git a/packages/core/src/Shared/lifecycle.ts b/packages/core/src/Shared/lifecycle.ts
index 7afacc92ab..97f67d2298 100644
--- a/packages/core/src/Shared/lifecycle.ts
+++ b/packages/core/src/Shared/lifecycle.ts
@@ -1,5 +1,5 @@
import { IDisposable } from '@wendellhu/redi';
-import { Subscription, SubscriptionLike } from 'rxjs';
+import { Subject, Subscription, SubscriptionLike } from 'rxjs';
import { isSubscription } from 'rxjs/internal/Subscription';
export function toDisposable(subscription: SubscriptionLike): IDisposable;
@@ -52,3 +52,13 @@ export class Disposable implements IDisposable {
this._collection.dispose();
}
}
+
+export class RxDisposable extends Disposable implements IDisposable {
+ protected dispose$ = new Subject<void>();
+
+ override dispose(): void {
+ super.dispose();
+ this.dispose$.next();
+ this.dispose$.complete();
+ }
+}
diff --git a/packages/core/src/Types/Interfaces/ICellData.ts b/packages/core/src/Types/Interfaces/ICellData.ts
index 7a005cdb95..9cf1e9bdbe 100644
--- a/packages/core/src/Types/Interfaces/ICellData.ts
+++ b/packages/core/src/Types/Interfaces/ICellData.ts
@@ -20,7 +20,10 @@ export interface ICellData {
// id?: string;
p?: IDocumentData; // univer docs
s?: string | Nullable<IStyleData>; // style id
- v?: Nullable<ICellV>; // origin value
+ /**
+ * Origin value
+ */
+ v?: Nullable<ICellV>;
m?: Nullable<string>; // formatted value
// Usually the type is automatically determined based on the data, or the user directly specifies
t?: CellValueType; // 0 string, 1 number, 2 boolean, 3 force string, green icon
diff --git a/packages/core/src/Types/Interfaces/ISelectionData.ts b/packages/core/src/Types/Interfaces/ISelectionData.ts
index 495fd4eb97..100617a36c 100644
--- a/packages/core/src/Types/Interfaces/ISelectionData.ts
+++ b/packages/core/src/Types/Interfaces/ISelectionData.ts
@@ -14,9 +14,7 @@ export interface IPosition {
export interface ISingleCell {
row: number; // current cell, if cell is in merge, isMerged is true, If the cell is in the upper left corner, isMergedMainCell is true.
column: number;
-
isMerged: boolean;
-
isMergedMainCell: boolean;
}
@@ -36,7 +34,8 @@ export enum SELECTION_TYPE {
}
export interface ISelection {
- rangeData: ISelectionRange;
+ /** range */
+ rangeData: ISelectionRange; // TODO@wzhudev: rename
cellRange: Nullable<ISelectionCell>;
selectionType?: SELECTION_TYPE;
}
diff --git a/packages/core/src/Types/Interfaces/ISelectionRange.ts b/packages/core/src/Types/Interfaces/ISelectionRange.ts
index 2cf9f00e10..dfdd4f11bc 100644
--- a/packages/core/src/Types/Interfaces/ISelectionRange.ts
+++ b/packages/core/src/Types/Interfaces/ISelectionRange.ts
@@ -13,6 +13,7 @@
*
* means "A1:B2"
*/
+// TODO@wzhudev: Rename to IRange
export interface ISelectionRange {
/**
* The start row (inclusive) of the range
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index baa387b95e..8e77d7e743 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,17 +1,6 @@
// Copyright (c) DreamNum Company. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
-/**
- * UniverSheet core package
- *
- * @remarks
- * The core defines basic data structures {@link IData} , APIs for modifying data {@link Domain},
- * easily extensible plugins {@link Plugin} and event listeners {@link Observer}
- *
- * @packageDocumentation
- *
- */
-
export * from './Basics';
export * from './Docs/Domain';
export * from './Observer';
@@ -25,6 +14,7 @@ export {
IMutation,
IOperation,
} from './services/command/command.service';
+export { IConfigService } from './services/config/config.service';
export { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE } from './services/context/context';
export { IContextService } from './services/context/context.service';
export { ICurrentUniverService } from './services/current.service';
@@ -35,7 +25,7 @@ export { DesktopLogService, ILogService } from './services/log/log.service';
export { DesktopPermissionService, IPermissionService } from './services/permission/permission.service';
export { IUndoRedoService, LocalUndoRedoService, RedoCommand, UndoCommand } from './services/undoredo/undoredo.service';
export * from './Shared';
-export { Disposable, DisposableCollection, fromObservable, toDisposable } from './Shared/lifecycle';
+export { Disposable, DisposableCollection, fromObservable, RxDisposable, toDisposable } from './Shared/lifecycle';
export { createRowColIter, IRowColIter } from './Shared/RowColIter';
export * from './Sheets';
export * from './Slides/Domain';
diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.ts
index 632f2471ff..d3840566e6 100644
--- a/packages/core/src/services/command/command.service.ts
+++ b/packages/core/src/services/command/command.service.ts
@@ -243,7 +243,7 @@ export class CommandService implements ICommandService {
};
// emit command execution info
- this._commandExecutedListeners.forEach((l) => l(commandInfo));
+ this._commandExecutedListeners.forEach((listener) => listener(commandInfo));
return result;
}
@@ -296,7 +296,8 @@ export class CommandService implements ICommandService {
params?: P
): Promise<R> {
this._log.log(
- `${'|-'.repeat(this._commandExecutingLevel)}[ICommandService]: executing command "${command.id}".`
+ '[CommandService]',
+ `${'|-'.repeat(this._commandExecutingLevel)}executing command "${command.id}".`
);
this._commandExecutingLevel++;
@@ -307,7 +308,6 @@ export class CommandService implements ICommandService {
} catch (e) {
result = false;
this._commandExecutingLevel = 0;
-
throw e;
}
@@ -356,7 +356,7 @@ class MultiCommand implements IMultiCommand {
for (const item of this._implementations) {
const preconditions = item.command.preconditions;
if (preconditions?.(contextService)) {
- logService.log(`[MultiCommand]: executing implementation "${item.command.name}".`);
+ logService.log(`[MultiCommand]`, `executing implementation "${item.command.name}".`);
const result = await item.injector.invoke(item.command.handler, params);
if (result) {
return true;
diff --git a/packages/core/src/services/config/config.service.ts b/packages/core/src/services/config/config.service.ts
new file mode 100644
index 0000000000..53bc8d88ed
--- /dev/null
+++ b/packages/core/src/services/config/config.service.ts
@@ -0,0 +1,32 @@
+import { createIdentifier } from '@wendellhu/redi';
+
+import { IKeyValue } from '../../Shared/Types';
+
+export const IConfigService = createIdentifier<IConfigService>('univer.config-service');
+
+export interface IConfigService {
+ getConfig<T>(id: string): T | undefined;
+}
+
+const BUILT_IN_CONFIG: IKeyValue = {
+ maxCellsPerSheet: 1_000_000,
+};
+
+export class ConfigService implements IConfigService {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ private readonly _config = new Map<string, any>();
+
+ constructor() {
+ this._initBuiltInConfig();
+ }
+
+ getConfig<T>(id: string): T | undefined {
+ return this._config.get(id) as T;
+ }
+
+ private _initBuiltInConfig(): void {
+ Object.keys(BUILT_IN_CONFIG).forEach((key) => {
+ this._config.set(key, BUILT_IN_CONFIG[key]);
+ });
+ }
+}
diff --git a/packages/core/src/services/lifecycle/lifecycle.service.ts b/packages/core/src/services/lifecycle/lifecycle.service.ts
index 940c872219..c759543d07 100644
--- a/packages/core/src/services/lifecycle/lifecycle.service.ts
+++ b/packages/core/src/services/lifecycle/lifecycle.service.ts
@@ -3,15 +3,20 @@ import { BehaviorSubject } from 'rxjs';
import { Disposable, toDisposable } from '../../Shared/lifecycle';
import { ILogService } from '../log/log.service';
-import { LifecycleStages, LifecycleToModules } from './lifecycle';
+import { LifecycleNameMap, LifecycleStages, LifecycleToModules } from './lifecycle';
export class LifecycleService extends Disposable {
- private _lifecycle$ = new BehaviorSubject<LifecycleStages>(LifecycleStages.Staring);
+ private _lifecycle$ = new BehaviorSubject<LifecycleStages>(LifecycleStages.Starting);
lifecycle$ = this._lifecycle$.asObservable();
constructor(@ILogService private readonly _logService: ILogService) {
super();
+
+ this._logService.log(
+ `[LifecycleService]`,
+ `lifecycle progressed to "${LifecycleNameMap[LifecycleStages.Starting]}".`
+ );
}
get stage(): LifecycleStages {
@@ -27,7 +32,7 @@ export class LifecycleService extends Disposable {
return;
}
- this._logService.log('[LifecycleService]: lifecycle progressed to ', stage, ' .');
+ this._logService.log('[LifecycleService]', `lifecycle progressed to "${LifecycleNameMap[stage]}".`);
this._lifecycle$.next(stage);
}
}
diff --git a/packages/core/src/services/lifecycle/lifecycle.ts b/packages/core/src/services/lifecycle/lifecycle.ts
index cb3150652f..e906864dc3 100644
--- a/packages/core/src/services/lifecycle/lifecycle.ts
+++ b/packages/core/src/services/lifecycle/lifecycle.ts
@@ -7,7 +7,7 @@ export const enum LifecycleStages {
/**
* Register plugins to Univer.
*/
- Staring,
+ Starting,
/**
* Univer business instances (UniverDoc / UniverSheet / UniverSlide) are created and services or controllers provided by
@@ -26,17 +26,30 @@ export const enum LifecycleStages {
Steady,
}
+export const LifecycleNameMap = {
+ [LifecycleStages.Starting]: 'Starting',
+ [LifecycleStages.Ready]: 'Ready',
+ [LifecycleStages.Rendered]: 'Rendered',
+ [LifecycleStages.Steady]: 'Steady',
+};
+
export const LifecycleToModules = new Map<LifecycleStages, Array<DependencyIdentifier<unknown>>>();
-// register some modules here that will automatically run when Univer progressed to a certain lifecycle stage
+/**
+ * Register some modules here that will automatically run when Univer progressed to a certain lifecycle stage
+ */
export function OnLifecycle(lifecycleStage: LifecycleStages, identifier: DependencyIdentifier<unknown>) {
const decorator = function decorator(_registerTarget: Ctor<unknown>) {
- if (!LifecycleToModules.has(lifecycleStage)) {
- LifecycleToModules.set(lifecycleStage, []);
- }
-
- LifecycleToModules.get(lifecycleStage)!.push(identifier);
+ runOnLifecycle(lifecycleStage, identifier);
};
return decorator;
}
+
+export function runOnLifecycle(lifecycleStage: LifecycleStages, identifier: DependencyIdentifier<unknown>) {
+ if (!LifecycleToModules.has(lifecycleStage)) {
+ LifecycleToModules.set(lifecycleStage, []);
+ }
+
+ LifecycleToModules.get(lifecycleStage)!.push(identifier);
+}
diff --git a/packages/core/src/services/log/log.service.ts b/packages/core/src/services/log/log.service.ts
index 268dbf24e2..6133575d44 100644
--- a/packages/core/src/services/log/log.service.ts
+++ b/packages/core/src/services/log/log.service.ts
@@ -19,7 +19,15 @@ export class DesktopLogService extends Disposable implements ILogService {
private logEnabled = true;
log(...args: any[]): void {
- if (this.logEnabled) {
+ if (!this.logEnabled || !args.length) {
+ return;
+ }
+
+ const firstArg = args[0];
+ const withTag = /^\[(.*?)\]/g.test(firstArg);
+ if (withTag) {
+ console.log(`\x1B[97;104m${firstArg}\x1B[0m:`, ...args.slice(1));
+ } else {
console.log(...args);
}
}
diff --git a/packages/sheets-plugin-formula/src/Controller/FormulaPromptController.ts b/packages/sheets-plugin-formula/src/Controller/FormulaPromptController.ts
index d9945043d0..4e443e36a0 100644
--- a/packages/sheets-plugin-formula/src/Controller/FormulaPromptController.ts
+++ b/packages/sheets-plugin-formula/src/Controller/FormulaPromptController.ts
@@ -1,4 +1,4 @@
-import { $$, ComponentManager, SlotManager } from '@univerjs/base-ui';
+import { ComponentManager, SlotManager } from '@univerjs/base-ui';
import { ObserverManager } from '@univerjs/core';
import { SheetContainerUIController } from '@univerjs/ui-plugin-sheets';
import { Inject } from '@wendellhu/redi';
@@ -67,15 +67,11 @@ export class FormulaPromptController {
}
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);
- });
+ // 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() {
@@ -92,7 +88,14 @@ export class FormulaPromptController {
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))
+ (event.shiftKey &&
+ (kcode === 37 ||
+ kcode === 38 ||
+ kcode === 39 ||
+ kcode === 40 ||
+ kcode === KeyCode.WIN ||
+ kcode === KeyCode.WIN_R ||
+ kcode === KeyCode.MENU))
) ||
kcode === 8 ||
kcode === 32 ||
@@ -119,7 +122,14 @@ export class FormulaPromptController {
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))
+ (event.shiftKey &&
+ (kcode === 37 ||
+ kcode === 38 ||
+ kcode === 39 ||
+ kcode === 40 ||
+ kcode === KeyCode.WIN ||
+ kcode === KeyCode.WIN_R ||
+ kcode === KeyCode.MENU))
) ||
kcode === 8 ||
kcode === 32 ||
diff --git a/packages/sheets-plugin-formula/src/FormulaPlugin.tsx b/packages/sheets-plugin-formula/src/FormulaPlugin.tsx
index 8bd4c0d4a3..9bfc922ff6 100644
--- a/packages/sheets-plugin-formula/src/FormulaPlugin.tsx
+++ b/packages/sheets-plugin-formula/src/FormulaPlugin.tsx
@@ -1,7 +1,6 @@
import { FormulaEngineService } from '@univerjs/base-formula-engine';
import { CellEditExtensionManager, CellInputExtensionManager } from '@univerjs/base-ui';
import { LocaleService, Plugin, PluginType } from '@univerjs/core';
-import { SheetContainerUIController } from '@univerjs/ui-plugin-sheets';
import { Dependency, Inject, Injector } from '@wendellhu/redi';
import { FORMULA_PLUGIN_NAME } from './Basics/Const/PLUGIN_NAME';
@@ -9,7 +8,6 @@ import { IFormulaConfig } from './Basics/Interfaces/IFormula';
import { FormulaPluginObserve, install } from './Basics/Observer';
import { FormulaCellEditExtensionFactory } from './Basics/Register/FormulaCellEditExtension';
import { FormulaCellInputExtensionFactory } from './Basics/Register/FormulaCellInputExtension';
-import { firstLoader } from './Controller/FirstLoader';
import { FormulaController } from './Controller/FormulaController';
import { FormulaPromptController } from './Controller/FormulaPromptController';
import { SearchFormulaController } from './Controller/SearchFormulaModalController';
@@ -26,8 +24,14 @@ export class FormulaPlugin extends Plugin<FormulaPluginObserve> {
private _formulaPromptController: FormulaPromptController;
- constructor(private _config: IFormulaConfig, @Inject(Injector) override readonly _injector: Injector, @Inject(LocaleService) private readonly _localeService: LocaleService) {
+ constructor(
+ private _config: IFormulaConfig,
+ @Inject(Injector) override readonly _injector: Injector,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
super(FORMULA_PLUGIN_NAME);
+
+ this.initializeDependencies(this._injector);
}
initialize(): void {
@@ -38,26 +42,6 @@ export class FormulaPlugin extends Plugin<FormulaPluginObserve> {
en,
});
- const sheetContainerUIController = this._injector.get(SheetContainerUIController);
-
- sheetContainerUIController.UIDidMount(() => {
- this.initializeDependencies(this._injector);
- this.registerExtension();
- const formulaBar = sheetContainerUIController.getFormulaBarUIController().getFormulaBar();
-
- const formulaEngineService = this._injector.get(FormulaEngineService);
- this._formulaController.setFormulaEngine(formulaEngineService);
-
- firstLoader(this._formulaController);
-
- formulaBar.setFx({
- onClick: () => {
- this._searchFormulaController.showFormulaModal('SearchFormula', true);
- },
- icon: 'FxIcon',
- });
- });
-
// this._arrayFormLineControl.addArrayFormLineToSheet(
// {
// startRow: 1,
@@ -90,7 +74,24 @@ export class FormulaPlugin extends Plugin<FormulaPluginObserve> {
override onRendered(): void {
install(this);
- this.initialize();
+ // setTimeout(() => {
+ // this.registerExtension();
+ // const sheetContainerUIController = this._injector.get(SheetContainerUIController);
+ // const formulaBar = sheetContainerUIController.getFormulaBarUIController().getFormulaBar();
+
+ // const formulaEngineService = this._injector.get(FormulaEngineService);
+ // this._formulaController.setFormulaEngine(formulaEngineService);
+
+ // firstLoader(this._formulaController);
+
+ // formulaBar.setFx({
+ // onClick: () => {
+ // this._searchFormulaController.showFormulaModal('SearchFormula', true);
+ // },
+ // icon: 'FxIcon',
+ // });
+ // this.initialize();
+ // }, 200);
}
override onDestroy(): void {
diff --git a/packages/sheets-plugin-numfmt/src/NumfmtPlugin.ts b/packages/sheets-plugin-numfmt/src/NumfmtPlugin.ts
index 1af84cd37f..13ec39b0ac 100644
--- a/packages/sheets-plugin-numfmt/src/NumfmtPlugin.ts
+++ b/packages/sheets-plugin-numfmt/src/NumfmtPlugin.ts
@@ -38,7 +38,6 @@ export class NumfmtPlugin extends Plugin {
this._numfmtController = this._injector.get(NumfmtController);
this._numfmtModalController = this._injector.get(NumfmtModalController);
this._localeService.getLocale().load({ en });
- // const actionRegister = this._commandManager.getActionExtensionManager().getRegister();
// actionRegister.add(this._numfmtActionExtensionFactory);
}
diff --git a/packages/ui-plugin-sheets/src/Basics/Interfaces/ComponentConfig/RightMenuConfig.ts b/packages/ui-plugin-sheets/src/Basics/Interfaces/ComponentConfig/RightMenuConfig.ts
deleted file mode 100644
index 8d56a8887d..0000000000
--- a/packages/ui-plugin-sheets/src/Basics/Interfaces/ComponentConfig/RightMenuConfig.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export interface SheetRightMenuConfig {
- InsertRow?: boolean;
- InsertColumn?: boolean;
- AddRowTop?: boolean;
- AddRowBottom?: boolean;
- AddColumnLeft?: boolean;
- AddColumnRight?: boolean;
- DeleteRow?: boolean;
- DeleteColumn?: boolean;
- HideRow?: boolean;
- ShowRow?: boolean;
- RowHeight?: boolean;
- HideColumn?: boolean;
- ShowColumn?: boolean;
- ColumnWidth?: boolean;
- DeleteCell?: boolean;
- ClearContent?: boolean;
- Matrix?: boolean;
-}
diff --git a/packages/ui-plugin-sheets/src/Basics/Interfaces/ComponentConfig/index.ts b/packages/ui-plugin-sheets/src/Basics/Interfaces/ComponentConfig/index.ts
index 7bf4584d51..ac0682d184 100644
--- a/packages/ui-plugin-sheets/src/Basics/Interfaces/ComponentConfig/index.ts
+++ b/packages/ui-plugin-sheets/src/Basics/Interfaces/ComponentConfig/index.ts
@@ -1,3 +1,2 @@
export * from './ISheetUIPluginConfig';
-export * from './RightMenuConfig';
export * from './ToolbarConfig';
diff --git a/packages/ui-plugin-sheets/src/View/Common/Line/LineBold.tsx b/packages/ui-plugin-sheets/src/View/Common/Line/LineBold.tsx
index 45a3e3d5ba..d632c2a27e 100644
--- a/packages/ui-plugin-sheets/src/View/Common/Line/LineBold.tsx
+++ b/packages/ui-plugin-sheets/src/View/Common/Line/LineBold.tsx
@@ -1,7 +1,7 @@
import { AppContext, BaseComponentProps, CustomLabel, Icon } from '@univerjs/base-ui';
import { Component } from 'react';
-import { BORDER_SIZE_CHILDREN } from '../../../controller/menu/border.menu';
+import { BORDER_SIZE_CHILDREN, LINE_BOLD_LABEL } from '../../../controller/menu/border.menu';
interface IState {
img: string;
@@ -14,7 +14,7 @@ interface IProps extends BaseComponentProps {
}
export class LineBold extends Component<IProps, IState> {
- static readonly componentName = 'bold';
+ static readonly componentName = LINE_BOLD_LABEL;
static override contextType = AppContext;
diff --git a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuButton.tsx b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuButton.tsx
deleted file mode 100644
index 4e4a5f7072..0000000000
--- a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuButton.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { Button } from '@univerjs/base-ui';
-import { Component } from 'react';
-
-interface IProps {
- label: string;
- children: IPropsChildren[];
-}
-
-interface IPropsChildren {
- label: string;
-}
-
-export class RightMenuButton extends Component<IProps> {
- override render() {
- const { label, children } = this.props;
-
- return (
- <div>
- {label}
- {children.map((item: IPropsChildren, index) => (
- <Button key={index} type="primary">
- {item.label}
- </Button>
- ))}
- </div>
- );
- }
-}
diff --git a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuSelect.tsx b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuSelect.tsx
deleted file mode 100644
index 708a29f8da..0000000000
--- a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuSelect.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-// import { Component, Input } from '@univerjs/base-ui';
-// import { CustomLabelOptions } from '../../Controller';
-
-// interface IProps {
-// label: string;
-// options: CustomLabelOptions[];
-// }
-
-// export class RightMenuSelect extends Component<IProps> {
-// render() {
-// const { label, options } = this.props;
-
-// return (
-// <div>
-// <div>{label}</div>
-// <select>
-// {options.map((item) => (
-// <option>{item.label}</option>
-// ))}
-// </select>
-// <Input type="number" placeholder="2"></Input>
-// </div>
-// );
-// }
-// }
diff --git a/packages/ui-plugin-sheets/src/View/RightMenu/index.ts b/packages/ui-plugin-sheets/src/View/RightMenu/index.ts
deleted file mode 100644
index 5b953c9cb0..0000000000
--- a/packages/ui-plugin-sheets/src/View/RightMenu/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export * from './RightMenu';
-export * from './RightMenuButton';
-export * from './RightMenuInput';
-export * from './RightMenuItem';
-
-// TODO: RightMenu should be renamed to ContextMenu. RightMenu is not a common name.
diff --git a/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx b/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
deleted file mode 100644
index 654cdd47d1..0000000000
--- a/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import {
- AppContext,
- Button,
- ButtonType,
- CustomLabel,
- IDisplayMenuItem,
- IMenuButtonItem,
- IMenuItem,
- IMenuSelectorItem,
- IValueOption,
- MenuItemType,
- Select,
- Tooltip,
-} from '@univerjs/base-ui';
-import { ICommandService, IKeyValue } from '@univerjs/core';
-import { Component } from 'react';
-import { Subscription } from 'rxjs';
-
-import styles from './index.module.less';
-
-export interface IToolbarItemStatus {
- disabled: boolean;
- activated: boolean;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- value: any;
-}
-
-/** The component to render toolbar item. */
-export class ToolbarItem extends Component<IDisplayMenuItem<IMenuItem>, IToolbarItemStatus> {
- static override contextType = AppContext;
-
- private disabledSubscription: Subscription | undefined;
-
- private activatedSubscription: Subscription | undefined;
-
- private currentValueSubscription: Subscription | undefined;
-
- constructor(props: IDisplayMenuItem<IMenuItem>) {
- super(props);
-
- this.state = {
- disabled: false,
- activated: false,
- value: undefined,
- };
- }
-
- override componentDidMount() {
- this.disabledSubscription = this.props.disabled$?.subscribe((disabled) => {
- this.setState({ disabled });
- });
-
- if (this.props.type === MenuItemType.BUTTON) {
- const props = this.props as IDisplayMenuItem<IMenuButtonItem>;
- this.activatedSubscription = props.activated$?.subscribe((activated) => {
- this.setState({ activated });
- });
- }
-
- if (this.props.type === MenuItemType.SELECTOR) {
- const props = this.props as IDisplayMenuItem<IMenuSelectorItem<unknown>>;
- this.currentValueSubscription = props.value$?.subscribe((value) => {
- this.setState({ value });
- });
- }
- }
-
- override UNSAFE_componentWillMount() {
- this.disabledSubscription?.unsubscribe();
- this.activatedSubscription?.unsubscribe();
- this.currentValueSubscription?.unsubscribe();
- }
-
- override render() {
- switch (this.props.type) {
- case MenuItemType.SUBITEMS:
- case MenuItemType.SELECTOR:
- return this.renderSelectorType();
- default:
- return this.renderButtonType();
- }
- }
-
- private renderSelectorType() {
- const { context, state } = this;
- const commandService: ICommandService = (context as IKeyValue).injector.get(ICommandService);
- const { disabled, value } = state;
-
- const props = this.props as IDisplayMenuItem<IMenuSelectorItem<unknown>>;
- const { icon, title, label, display, selectType, selections, id } = props;
-
- return (
- <Tooltip title={this.getTooltip()} placement="bottom">
- <Select
- id={id}
- title={title}
- children={selections! as IValueOption[]}
- options={selections as IValueOption[]}
- display={display}
- icon={icon}
- value={value}
- label={value ?? label} // TODO: this line is strange
- onClick={({ value, id: selectorId }) => {
- commandService.executeCommand(selectorId ?? id, { value });
- }} // TODO@wzhudev: should be merged to a single API on value change
- onPressEnter={(value) => commandService.executeCommand(id, { value })}
- type={selectType!}
- ></Select>
- </Tooltip>
- );
- }
-
- private renderButtonType() {
- const { props, context, state } = this;
- const { disabled, activated } = state;
- const { icon, title } = props;
- const commandService: ICommandService = (context as IKeyValue).injector.get(ICommandService);
-
- return (
- <Tooltip title={this.getTooltip()} placement="bottom">
- <Button active={activated} className={styles.textButton} type={'text' as ButtonType} disabled={disabled} onClick={() => commandService.executeCommand(props.id)}>
- <CustomLabel label={icon ? { name: icon } : title} />
- </Button>
- </Tooltip>
- );
- }
-
- private getTooltip(): string {
- return (this.context as IKeyValue).localeService?.t(this.props.tooltip) + (this.props.shortcut ? ` (${this.props.shortcut})` : '');
- }
-}
diff --git a/packages/ui-plugin-sheets/src/View/Toolbar/index.less b/packages/ui-plugin-sheets/src/View/Toolbar/index.less
deleted file mode 100644
index 04f1f4201e..0000000000
--- a/packages/ui-plugin-sheets/src/View/Toolbar/index.less
+++ /dev/null
@@ -1,310 +0,0 @@
-.universheet-wa-editor.toolbar {
- height: 32px;
- background: var(--bg);
- position: relative;
- padding: 5px 0 3px 15px;
- border-bottom: 1px solid var(--bg);
- white-space: nowrap;
- transition: all 0.2s;
- box-sizing: initial;
-
- span[role='img'] {
- font-size: 24px;
- display: inline-block;
- }
-
- span[role='img'].univericon-nextIcon {
- font-size: 13px;
- }
-
- span[role='img'].univericon-rightIcon {
- font-size: 13px;
- }
-
- .universheet-toolbar-left-skin {
- width: 15px;
- position: absolute;
- left: 0;
- top: 1px;
- bottom: 1px;
- }
-
- .universheet-inline-block {
- display: inline-block;
- }
-
- .universheet-flex {
- display: flex;
- }
-
- .universheet-toolbar-button,
- .universheet-toolbar-menu-button {
- vertical-align: middle;
-
- &:hover {
- background: rgba(0, 0, 0, 0.06);
- }
-
- button {
- min-width: 26px;
- height: 26px;
- padding: 0;
- border: none;
- .toolbar-button();
-
- span {
- height: 100%;
- vertical-align: text-bottom;
- }
- }
- }
-
- .universheet-toolbar-button-outer-box,
- .universheet-toolbar-menu-button-outer-box {
- .outer-inner-box();
- }
-
- .universheet-toolbar-select {
- position: relative;
- }
-
- .universheet-toolbar-button-inner-box,
- .universheet-toolbar-menu-button-inner-box {
- padding: 0 2px;
- padding: 0;
- text-align: center;
- height: 26px;
- min-width: 26px;
- font-size: 12px;
- }
-
- .universheet-toolbar-menu-button-caption {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- margin-left: 1px;
- text-align: center;
- height: 100%;
- }
-
- .universheet-toolbar-menu-button-text {
- width: 55px !important;
- }
-
- .universheet-toolbar-separator {
- line-height: normal;
- list-style: none;
- outline: 0;
- overflow: hidden;
- padding: 0;
- text-decoration: none;
- width: 0;
- height: 20px;
- vertical-align: top;
- border-left: 1px solid #e0e0e0;
- margin: 5px 1px;
- }
-
- .universheet-toolbar-combo-button {
- font-weight: 700;
- vertical-align: inherit;
- margin: 0 1px;
- .toolbar-button();
- }
-
- .universheet-toolbar-combo-button-inner-box,
- .universheet-toolbar-combo-button-outer-box {
- .outer-inner-box();
- }
-
- .universheet-toolbar-zoom-combobox .universheet-toolbar-combo-button-caption {
- width: 36px !important;
- }
-
- .universheet-toolbar-combo-button-caption {
- padding: 0;
- margin: 0 0 0 -3px;
- }
-
- .universheet-toolbar-textinput {
- -webkit-border-radius: 1px;
- -moz-border-radius: 1px;
- border-radius: 1px;
- border: 1px solid #d9d9d9;
- border-top: 1px solid silver;
- font-size: 13px;
- height: 25px;
- padding: 1px 0 1px 8px;
- }
-
- .universheet-toolbar-combo-button-input {
- background: 0 0;
- border: 1px solid transparent !important;
- color: var(--text-color);
- font-family: Arial, sans-serif !important;
- font-size: 11px !important;
- font-weight: 700 !important;
- height: 20px !important;
- overflow: hidden !important;
- color: rgba(0, 0, 0, 0.7);
- height: 22px !important;
- width: 22px;
- }
-
- .universheet-cols-menu {
- .menu-button();
- width: 252px;
- left: 0;
- top: 26px;
- display: none;
- }
-
- .universheet-cols-menu .universheet-cols-menuitem-hover,
- .universheet-cols-menu .universheet-cols-menuitem:hover {
- background-color: #efefef;
- }
-
- .universheet-cols-menu .universheet-cols-menuitem {
- position: relative;
- color: var(--text-color);
- cursor: pointer;
- list-style: none;
- margin: 0;
- padding: 1px 6em 1px 20px;
- white-space: nowrap;
- padding-left: 8px;
- vertical-align: middle;
- padding-right: 24px;
- user-select: none;
- line-height: 16px;
- }
-
- .universheet-submenu-arrow {
- -webkit-transition: all 218ms;
- -moz-transition: all 218ms;
- -o-transition: all 218ms;
- transition: all 218ms;
- font-size: 12px;
- left: auto;
- right: 15px;
- top: 50%;
- transform: translateY(-50%);
- padding-right: 0;
- position: absolute;
- text-align: right;
- opacity: 0.5;
- color: #000;
- user-select: none;
- font-family: Arial;
- }
-
- .universheet-toolbar-dblbutton {
- .universheet-toolbar-next-button {
- border-left: 1px solid transparent;
- position: relative;
-
- .universheet-next-menu {
- position: absolute;
- z-index: 2;
- background-color: #fff;
- box-shadow: var(--box-shadow-base);
- font-size: 12px;
- width: fit-content;
-
- .univer-menu-item > div {
- width: 100%;
- display: flex;
- justify-content: space-between;
- box-sizing: border-box;
- padding: 0 5px 0 0;
-
- .universheet-next-menu-icon {
- width: 25px;
-
- & ~ div {
- flex: 1;
- display: flex;
- justify-content: space-between;
- align-items: center;
- }
- }
- }
-
- svg {
- font-size: 24px;
- vertical-align: top;
- }
- }
-
- svg {
- font-size: 12px;
- vertical-align: middle;
- }
- }
-
- .universheet-color-bottom {
- width: 10px;
- margin: 0 auto;
- outline: 2px solid;
- position: relative;
- bottom: 7px;
- }
-
- button.univer-btn {
- min-width: 15px;
-
- &:active {
- background: transparent !important;
- }
- }
-
- :hover .universheet-toolbar-next-button {
- border-left: 1px solid #e0e0e0;
- }
- }
-}
-
-// 重复样式
-.outer-inner-box() {
- border: 0;
- vertical-align: top;
- margin: 0;
- padding: 0;
-}
-
-.toolbar-button() {
- -webkit-border-radius: 2px;
- -moz-border-radius: 2px;
- border-radius: 2px;
- -webkit-user-select: none;
- -moz-user-select: none;
- -ms-user-select: none;
- background: 0;
- border: 1px solid transparent;
- outline: 0;
- padding: 0;
- list-style: none;
- font-size: 11px;
- text-decoration: none;
- cursor: default;
- height: 26px;
- line-height: 26px;
- color: var(--text-color);
-}
-
-.menu-button() {
- border-radius: 0;
- box-shadow: 0 2px 4px rgb(0 0 0 / 20%);
- transition: opacity 218ms;
- background: #fff;
- border: 1px solid rgba(0, 0, 0, 0.2);
- cursor: default;
- font-size: 13px;
- margin: 0;
- outline: 0;
- padding: 6px 0;
- position: absolute;
- z-index: 2;
- box-sizing: border-box;
- user-select: none;
-}
diff --git a/packages/ui-plugin-sheets/src/View/Toolbar/index.module.less b/packages/ui-plugin-sheets/src/View/Toolbar/index.module.less
deleted file mode 100644
index e99f17bd85..0000000000
--- a/packages/ui-plugin-sheets/src/View/Toolbar/index.module.less
+++ /dev/null
@@ -1,176 +0,0 @@
-.toolbar-warp {
- max-height: fit-content;
- width: 100%;
- overflow: unset;
- box-sizing: border-box;
- font-size: var(--font-size);
- background-color: var(--bg);
- position: relative;
- display: flex;
- align-items: center;
- border-bottom: 1px solid var(--border-color-base);
-
- .single-button {
- &.more-hide {
- display: none;
- }
-
- &.more-show {
- display: block;
- }
- }
-}
-
-.toolbar {
- max-width: 100%;
- color: var(--text-color);
- padding: 0 15px;
- height: 40px;
- position: relative;
- display: flex;
- align-items: center;
-
- >div {
- height: 26px;
- display: inline-block;
- vertical-align: middle;
- margin: 0 3px;
- cursor: pointer;
-
- &.select-button:hover {
- background-color: #efefef;
- }
- }
-
- .cols-menu {
- overflow-y: auto;
- }
-
- .select-label-string {
- .drop-content {
- >div {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- width: 90px;
- }
- }
- }
-
- .select-double-string {
- .drop-content {
- >div {
- width: 24px;
- }
- }
- }
-
- .select-color-picker-parent {
- .select-item-content {
- width: 100%;
- }
-
- .select-color-picker {
- cursor: default;
-
- &:hover {
- background: var(--bg);
- }
-
- .select-item {
- padding: 0;
- }
-
- .color-picker-outer {
- box-shadow: none;
- }
- }
- }
-
- .select-line-bold-parent {
- .select-item-content {
- width: 100%;
- }
- }
-
- .select-single {
- height: 26px;
- line-height: 26px;
- }
-
- .select-input {
- height: 26px;
- line-height: 26px;
- }
-
- .select-double {
- height: 26px;
- line-height: 26px;
- }
-
- button {
- padding: 0;
- height: 26px;
- }
-
- span[role='img'].univericon-nextIcon {
- font-size: 12px;
- }
-
- .text-button {
- span[role="img"] {
- font-size: 24px;
- }
-
- button {
- padding: 0 5px;
- }
- }
-
-}
-
-.more-button {
- position: absolute;
- right: 15px;
- top: 50%;
- transform: translateY(-50%);
- .button();
-
- &.more-show {
- display: block;
- }
-}
-
-.more-tool {
- // height: 40px;
- // display: none;
- // align-items: center;
- padding: 0 10px;
- background-color: var(--bg);
- box-shadow: var(--box-shadow-base);
- position: absolute;
- right: 2em;
- top: 40px;
- z-index: 2;
-
- &.more-show {
- display: flex;
- }
-
- button {
- .button();
- }
-}
-
-.button() {
- padding: 0px;
- line-height: 1;
-}
-
-.tooltip-title {
- opacity: 1;
-}
-
-.bottom {
- display: none;
-}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
index 543367d363..b0722efc0e 100644
--- a/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
+++ b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
@@ -1,8 +1,8 @@
-import { CopyCommand, CutCommand, PasteCommand } from '@univerjs/base-ui';
-import { CommandType, FOCUSING_SHEET, IContextService, IMultiCommand } from '@univerjs/core';
+import { CopyCommand, CutCommand, IClipboardInterfaceService, PasteCommand } from '@univerjs/base-ui';
+import { CommandType, FOCUSING_SHEET, IContextService, ILogService, IMultiCommand } from '@univerjs/core';
import { ISheetClipboardService } from '../../services/clipboard/clipboard.service';
-import { FOCUSING_SHEET_EDITOR } from '../../services/context/context';
+import { SHEET_EDITOR_ACTIVATED } from '../../services/context/context';
export const SheetCopyCommand: IMultiCommand = {
id: CopyCommand.id,
@@ -11,7 +11,7 @@ export const SheetCopyCommand: IMultiCommand = {
multi: true,
priority: 1000,
preconditions: (contextService: IContextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_EDITOR),
+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(SHEET_EDITOR_ACTIVATED),
handler: async (accessor) => {
const sheetClipboardService = accessor.get(ISheetClipboardService);
return sheetClipboardService.copy();
@@ -25,10 +25,11 @@ export const SheetCutCommand: IMultiCommand = {
multi: true,
priority: 1000,
preconditions: (contextService: IContextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_EDITOR),
- handler: async (accessor, params) =>
- // TODO@wzhudev: the same as SheetCopyCommand but we should dispatch a delete command as well
- true,
+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(SHEET_EDITOR_ACTIVATED),
+ handler: async (accessor, params) => {
+ const sheetClipboardService = accessor.get(ISheetClipboardService);
+ return sheetClipboardService.cut();
+ },
};
export const SheetPasteCommand: IMultiCommand = {
@@ -38,6 +39,34 @@ export const SheetPasteCommand: IMultiCommand = {
name: 'sheet.command.paste',
priority: 1000,
preconditions: (contextService: IContextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_EDITOR),
- handler: async (accessor, params) => true,
+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(SHEET_EDITOR_ACTIVATED),
+ handler: async (accessor) => {
+ const logService = accessor.get(ILogService);
+
+ // use cell editor to get ClipboardData first
+ // if that doesn't work, use the browser's clipboard API
+ // this clipboard API would ask user for permission, so we may need to notify user (and retry perhaps)
+ logService.log('[SheetPasteCommand]', 'the focusing element is', document.activeElement);
+
+ const result = document.execCommand('paste');
+ if (!result) {
+ logService.log(
+ '[SheetPasteCommand]',
+ 'failed to execute paste command on the activeElement, trying to use clipboard API.'
+ );
+
+ const clipboardInterfaceService = accessor.get(IClipboardInterfaceService);
+ const clipboardItems = await clipboardInterfaceService.read();
+ const sheetClipboardService = accessor.get(ISheetClipboardService);
+
+ // logService.log('[SheetPasteCommand]: clipboard data is', clipboardItems);
+ if (clipboardItems.length !== 0) {
+ return sheetClipboardService.paste(clipboardItems[0]);
+ }
+
+ return false;
+ }
+
+ return false;
+ },
};
diff --git a/packages/ui-plugin-sheets/src/commands/rename.command.ts b/packages/ui-plugin-sheets/src/commands/commands/rename.command.ts
similarity index 100%
rename from packages/ui-plugin-sheets/src/commands/rename.command.ts
rename to packages/ui-plugin-sheets/src/commands/commands/rename.command.ts
diff --git a/packages/ui-plugin-sheets/src/commands/unhide.command.ts b/packages/ui-plugin-sheets/src/commands/commands/unhide.command.ts
similarity index 100%
rename from packages/ui-plugin-sheets/src/commands/unhide.command.ts
rename to packages/ui-plugin-sheets/src/commands/commands/unhide.command.ts
diff --git a/packages/ui-plugin-sheets/src/controller/SheetBarUIController.ts b/packages/ui-plugin-sheets/src/controller/SheetBarUIController.ts
index 7b4e9cd88e..f3fae65f03 100644
--- a/packages/ui-plugin-sheets/src/controller/SheetBarUIController.ts
+++ b/packages/ui-plugin-sheets/src/controller/SheetBarUIController.ts
@@ -3,8 +3,8 @@ import { BooleanNumber, Disposable, ICommandService, LifecycleStages, Nullable,
import { Inject, Injector } from '@wendellhu/redi';
import { SHEET_UI_PLUGIN_NAME } from '../Basics/Const';
-import { RenameSheetCommand } from '../commands/rename.command';
-import { ShowMenuListCommand } from '../commands/unhide.command';
+import { RenameSheetCommand } from '../commands/commands/rename.command';
+import { ShowMenuListCommand } from '../commands/commands/unhide.command';
import { SheetBar } from '../View/SheetBar';
import {
ChangeColorSheetMenuItemFactory,
diff --git a/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts b/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
index 8d8f87c228..9cb7760e35 100644
--- a/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
@@ -1,20 +1,52 @@
import {
+ InsertColMutation,
+ InsertRowMutation,
+ ISetRangeValuesMutationParams,
+ SetRangeValuesMutation,
+} from '@univerjs/base-sheets';
+import {
+ IInsertColMutationParams,
+ IInsertRowMutationParams,
+} from '@univerjs/base-sheets/Basics/Interfaces/MutationInterface.js';
+import {
+ ISetWorksheetColWidthMutationParams,
+ SetWorksheetColWidthMutation,
+} from '@univerjs/base-sheets/commands/mutations/set-worksheet-col-width.mutation.js';
+import {
+ ISetWorksheetRowHeightMutationParams,
+ SetWorksheetRowHeightMutation,
+} from '@univerjs/base-sheets/commands/mutations/set-worksheet-row-height.mutation.js';
+import { IMessageService } from '@univerjs/base-ui';
+import {
+ BooleanNumber,
Disposable,
+ ICellData,
+ ICommandInfo,
ICommandService,
+ IConfigService,
ICurrentUniverService,
+ ISelectionRange,
LifecycleStages,
+ LocaleService,
+ ObjectArray,
+ ObjectMatrix,
OnLifecycle,
Worksheet,
WrapStrategy,
} from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
import { SheetCopyCommand, SheetCutCommand, SheetPasteCommand } from '../../commands/commands/clipboard.command';
import {
IClipboardPropertyItem,
+ IParsedCellValue,
ISheetClipboardHook,
ISheetClipboardService,
} from '../../services/clipboard/clipboard.service';
+// TODO: default row height from config?
+const DEFAULT_HEIGHT = 20;
+
/**
* This controller add basic clipboard logic for basic features such as text color / BISU / row widths to the clipboard
* service. You can create a similar clipboard controller to add logic for your own features.
@@ -24,38 +56,49 @@ export class SheetClipboardController extends Disposable {
constructor(
@ICurrentUniverService private readonly _currentUniverSheet: ICurrentUniverService,
@ICommandService private readonly _commandService: ICommandService,
- @ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService
+ @IConfigService private readonly _configService: IConfigService,
+ @ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService,
+ @IMessageService private readonly _messageService: IMessageService,
+ @Inject(Injector) private readonly _injector: Injector,
+ @Inject(LocaleService) private readonly _localService: LocaleService
) {
super();
+
+ this._init();
}
- initialize() {
+ private _init() {
+ // register sheet clipboard commands
[SheetCopyCommand, SheetCutCommand, SheetPasteCommand].forEach((command) =>
this.disposeWithMe(this._commandService.registerAsMultipleCommand(command))
);
- let currentSheet: Worksheet | null = null;
+ // register basic sheet clipboard hooks
+ this.disposeWithMe(
+ this._sheetClipboardService.addClipboardHook({
+ ...this._initCopyingHooks(),
+ ...this._initPastingHook(),
+ })
+ );
+ }
+ private _initCopyingHooks(): ISheetClipboardHook {
const self = this;
- const hook: ISheetClipboardHook = {
- onBeforeCopy() {
- // before copy, we should update the current sheet
- // and create necessary cache if needed
- currentSheet = self._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let currentSheet: Worksheet | null = null;
+ return {
+ onBeforeCopy(workbookId, worksheetId) {
+ currentSheet = self._getWorksheet(workbookId, worksheetId);
},
- onGetContent(row: number, col: number): string {
+ onCopyCellContent(row: number, col: number): string {
const v = currentSheet!.getCellMatrix().getValue(row, col);
return v?.m || '';
},
- onCopy: (row: number, col: number, rowSpan?: number, colSpan?: number) => {
- // TODO: get cell style and write it into clipboard property item
+ onCopyCellStyle: (row: number, col: number, rowSpan?: number, colSpan?: number) => {
const properties: IClipboardPropertyItem = {};
- if (rowSpan) {
- properties.rowspan = `${rowSpan}`;
- }
- if (colSpan) {
- properties.colspan = `${colSpan}`;
+ if (rowSpan || colSpan) {
+ properties.rowspan = `${rowSpan || 1}`;
+ properties.colspan = `${colSpan || 1}`;
}
const range = currentSheet!.getRange(row, col);
@@ -116,7 +159,198 @@ export class SheetClipboardController extends Disposable {
currentSheet = null;
},
};
+ }
+
+ private _initPastingHook(): ISheetClipboardHook {
+ const self = this;
+
+ let workbookId: string | null = null;
+ let worksheetId: string | null = null;
+ let currentSheet: Worksheet | null = null;
+
+ return {
+ onBeforePaste(workbookId_, worksheetId_, range) {
+ currentSheet = self._getWorksheet(workbookId_, worksheetId_);
+ workbookId = workbookId_;
+ worksheetId = worksheetId_;
+
+ // examine if pasting would cause number of cells to exceed the upper limit
+ // this is not implemented yet
+ const maxConfig = self._configService.getConfig<number>('maxCellsPerSheet');
+ const { endRow, endColumn } = range;
+ if (maxConfig && endRow * endColumn > maxConfig) {
+ self._messageService.show(); // TODO: show error info
+ return false;
+ }
+
+ return true;
+ },
+
+ onPasteRows(range, rowProperties) {
+ const redoMutations: ICommandInfo[] = [];
+ const undoMutations: ICommandInfo[] = [];
+
+ // if the range is outside ot the worksheet's boundary, we should add rows
+ const maxRow = currentSheet!.getMaxRows();
+ const addingRowsCount = range.endRow - maxRow;
+ const existingRowsCount = rowProperties.length - addingRowsCount;
+ if (addingRowsCount > 0) {
+ const addRowMutation: IInsertRowMutationParams = {
+ workbookId: workbookId!,
+ worksheetId: worksheetId!,
+ ranges: [{ ...range, startRow: maxRow }],
+ rowInfo: new ObjectArray(
+ rowProperties.slice(existingRowsCount).map((property) => ({
+ h: property.height ? +property.height : DEFAULT_HEIGHT,
+ hd: BooleanNumber.FALSE,
+ }))
+ ),
+ };
+ redoMutations.push({
+ id: InsertRowMutation.id,
+ params: addRowMutation,
+ });
+ }
+
+ // apply row properties to the existing rows
+ const setRowPropertyMutation: ISetWorksheetRowHeightMutationParams = {
+ workbookId: workbookId!,
+ worksheetId: worksheetId!,
+ ranges: [{ ...range, endRow: Math.min(range.endRow, maxRow) }],
+ rowHeight: new ObjectArray(
+ rowProperties
+ .slice(0, existingRowsCount)
+ .map((property) => (property.height ? +property.height : DEFAULT_HEIGHT))
+ ),
+ };
+ redoMutations.push({
+ id: SetWorksheetRowHeightMutation.id,
+ params: setRowPropertyMutation,
+ });
+
+ // TODO: add undo mutations but we cannot do it now because underlying mechanism is not ready
+
+ return {
+ redos: [] || redoMutations,
+ undos: [] || undoMutations,
+ };
+ },
+
+ onPasteColumns(range, colProperties) {
+ const redoMutations: ICommandInfo[] = [];
+ const undoMutations: ICommandInfo[] = [];
+
+ // if the range is outside ot the worksheet's boundary, we should add rows
+ const maxColumn = currentSheet!.getMaxColumns();
+ const addingColsCount = range.endColumn - maxColumn;
+ const existingColsCount = colProperties.length - addingColsCount;
+ if (addingColsCount > 0) {
+ const addColMutation: IInsertColMutationParams = {
+ workbookId: workbookId!,
+ worksheetId: worksheetId!,
+ ranges: [{ ...range, startColumn: maxColumn }],
+ colInfo: new ObjectArray(
+ colProperties.slice(existingColsCount).map((property) => ({
+ w: property.width ? +property.width : DEFAULT_HEIGHT,
+ hd: BooleanNumber.FALSE,
+ }))
+ ),
+ };
+ redoMutations.push({
+ id: InsertColMutation.id,
+ params: addColMutation,
+ });
+ }
+
+ // apply row properties to the existing rows
+ const setRowPropertyMutation: ISetWorksheetColWidthMutationParams = {
+ workbookId: workbookId!,
+ worksheetId: worksheetId!,
+ ranges: [{ ...range, endRow: Math.min(range.endColumn, maxColumn) }],
+ colWidth: new ObjectArray(
+ colProperties
+ .slice(0, existingColsCount)
+ .map((property) => (property.width ? +property.width : DEFAULT_HEIGHT))
+ ),
+ };
+ redoMutations.push({
+ id: SetWorksheetColWidthMutation.id,
+ params: setRowPropertyMutation,
+ });
+
+ // TODO: add undo mutations but we cannot do it now because underlying mechanism is not ready
+
+ return {
+ redos: [] || redoMutations,
+ undos: [] || undoMutations,
+ };
+ },
+
+ onPasteCells(range, matrix) {
+ return self._onPasteCells(range, matrix, workbookId, worksheetId);
+ },
+
+ onAfterPaste(success) {
+ currentSheet = null;
+ },
+ };
+ }
+
+ private _onPasteCells(
+ range: ISelectionRange,
+ matrix: ObjectMatrix<IParsedCellValue>,
+ workbookId: string,
+ worksheetId: string
+ ): {
+ redos: ICommandInfo[];
+ undos: ICommandInfo[];
+ } {
+ // insert cell style, insert cell content and insert merged cell info
+ // 1. merged cell (TODO)
+ // 2. raw content
+ // 3. cell style (TODO)
+
+ const { startColumn, startRow } = range;
+ const valueMatrix = new ObjectMatrix<ICellData>();
+ const redoMutationsInfo: ICommandInfo[] = [];
+ const undoMutationsInfo: ICommandInfo[] = [];
+
+ matrix.forValue((row, col, value) => {
+ valueMatrix.setValue(row + startRow, col + startColumn, {
+ v: value.content,
+ });
+ });
+
+ const setContentMutation: ISetRangeValuesMutationParams = {
+ workbookId,
+ worksheetId,
+ rangeData: [range],
+ cellValue: valueMatrix.getData(),
+ };
+
+ redoMutationsInfo.push({
+ id: SetRangeValuesMutation.id,
+ params: setContentMutation,
+ });
+
+ return {
+ redos: redoMutationsInfo,
+ undos: undoMutationsInfo,
+ };
+ }
+
+ private _getWorksheet(workbookId: string, worksheetId: string): Worksheet {
+ const worksheet = this._currentUniverSheet
+ .getUniverSheetInstance(workbookId)
+ ?.getWorkBook()
+ .getSheetBySheetId(worksheetId);
+
+ if (!worksheet) {
+ throw new Error(
+ `[SheetClipboardController]: cannot find a worksheet with workbookId ${workbookId} and worksheetId ${worksheetId}.`
+ );
+ }
- this.disposeWithMe(this._sheetClipboardService.addClipboardHook(hook));
+ return worksheet;
}
}
diff --git a/packages/ui-plugin-sheets/src/controller/menu.ts b/packages/ui-plugin-sheets/src/controller/menu.ts
index b70ee70b4d..f36342a959 100644
--- a/packages/ui-plugin-sheets/src/controller/menu.ts
+++ b/packages/ui-plugin-sheets/src/controller/menu.ts
@@ -35,11 +35,13 @@ import {
import {
ColorPicker,
CopyCommand,
+ CutCommand,
DisplayTypes,
IMenuButtonItem,
IMenuSelectorItem,
MenuItemType,
MenuPosition,
+ PasteCommand,
SelectTypes,
} from '@univerjs/base-ui';
import {
@@ -60,8 +62,8 @@ import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { SHEET_UI_PLUGIN_NAME } from '../Basics/Const/PLUGIN_NAME';
-import { RenameSheetCommand } from '../commands/rename.command';
-import { ShowMenuListCommand } from '../commands/unhide.command';
+import { RenameSheetCommand } from '../commands/commands/rename.command';
+import { ShowMenuListCommand } from '../commands/commands/unhide.command';
export const CONTEXT_MENU_INPUT_LABEL = 'CONTEXT_MENU_INPUT';
@@ -93,8 +95,6 @@ export function RedoMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
};
}
-// TODO@wzhudev: in the future we will support add rich format value to in-cell texts. Then we would make some changes to how these menu items works.
-
export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const commandService = accessor.get(ICommandService);
const permissionService = accessor.get(IPermissionService);
@@ -893,6 +893,9 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
};
}
+// #region - copy cut paste
+// TODO@wzhudev: maybe we should move these menu factory to base-ui
+
export function CopyMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
return {
id: CopyCommand.id,
@@ -902,6 +905,26 @@ export function CopyMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
};
}
+export function CutMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ return {
+ id: CutCommand.id,
+ type: MenuItemType.BUTTON,
+ title: 'contextMenu.cut',
+ positions: [MenuPosition.CONTEXT_MENU],
+ };
+}
+
+export function PasteMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ return {
+ id: PasteCommand.id,
+ type: MenuItemType.BUTTON,
+ title: 'rightClick.paste',
+ positions: [MenuPosition.CONTEXT_MENU],
+ };
+}
+
+// #endregion
+
export function ClearSelectionMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
return {
id: ClearSelectionContentCommand.id,
diff --git a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
index 887f626b06..9c13b034f0 100644
--- a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
@@ -40,6 +40,7 @@ import {
InsertColMenuItemFactory,
InsertRowMenuItemFactory,
ItalicMenuItemFactory,
+ PasteMenuItemFactory,
RedoMenuItemFactory,
RemoveColMenuItemFactory,
RemoveRowMenuItemFactory,
@@ -142,6 +143,8 @@ export class SheetUIController extends Disposable {
[
// context menu
CopyMenuItemFactory,
+ PasteMenuItemFactory,
+
ClearSelectionMenuItemFactory,
InsertRowMenuItemFactory,
InsertColMenuItemFactory,
diff --git a/packages/ui-plugin-sheets/src/controller/shortcuts/style.shortcut.ts b/packages/ui-plugin-sheets/src/controller/shortcuts/style.shortcut.ts
index 0c0044d944..f7fe4026db 100644
--- a/packages/ui-plugin-sheets/src/controller/shortcuts/style.shortcut.ts
+++ b/packages/ui-plugin-sheets/src/controller/shortcuts/style.shortcut.ts
@@ -2,32 +2,32 @@ import { SetBoldCommand, SetItalicCommand, SetStrikeThroughCommand, SetUnderline
import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';
import { FOCUSING_SHEET } from '@univerjs/core';
-import { FOCUSING_SHEET_CELL_EDITOR } from '../../services/context/context';
+import { SHEET_EDITOR_ACTIVATED } from '../../services/context/context';
export const SetBoldShortcutItem: IShortcutItem = {
id: SetBoldCommand.id,
preconditions: (contextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),
+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(SHEET_EDITOR_ACTIVATED),
binding: KeyCode.B | MetaKeys.CTRL_COMMAND,
};
export const SetItalicShortcutItem: IShortcutItem = {
id: SetItalicCommand.id,
preconditions: (contextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),
+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(SHEET_EDITOR_ACTIVATED),
binding: KeyCode.I | MetaKeys.CTRL_COMMAND,
};
export const SetUnderlineShortcutItem: IShortcutItem = {
id: SetUnderlineCommand.id,
preconditions: (contextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),
+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(SHEET_EDITOR_ACTIVATED),
binding: KeyCode.U | MetaKeys.CTRL_COMMAND,
};
export const SetStrikeThroughShortcutItem: IShortcutItem = {
id: SetStrikeThroughCommand.id,
preconditions: (contextService) =>
- contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),
+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(SHEET_EDITOR_ACTIVATED),
binding: KeyCode.X | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,
};
diff --git a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts
index c0b0b97e57..4be7e9b15e 100644
--- a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts
+++ b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts
@@ -18,9 +18,9 @@ import {
SelectionManagerService,
SetRangeValuesCommand,
} from '@univerjs/base-sheets';
+import { IClipboardService } from '@univerjs/base-ui';
import {
createEmptyDocSnapshot,
- Disposable,
handleJsonToDom,
ICommandService,
IContextService,
@@ -32,11 +32,14 @@ import {
LifecycleStages,
Nullable,
OnLifecycle,
+ RxDisposable,
toDisposable,
} from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
+import { takeUntil } from 'rxjs';
-import { FOCUSING_SHEET_CELL_EDITOR, FOCUSING_SHEET_EDITOR } from '../context/context';
+import { ISheetClipboardService } from '../clipboard/clipboard.service';
+import { SHEET_EDITOR_ACTIVATED } from '../context/context';
import { ICellEditorService } from './cell-editor.service';
import { getPositionOfCurrentCell, ICellPosition } from './utils';
@@ -47,9 +50,11 @@ const SHEET_CELL_EDITOR_MODEL_ID = 'sheet.model.cell-editor';
/**
* Cell editor for Univer on desktop. Reuse by multi univer sheet documents.
+ *
+ * This service would also handle paste event for UniverSheet.
*/
@OnLifecycle(LifecycleStages.Rendered, ICellEditorService)
-export class DesktopCellEditorService extends Disposable implements ICellEditorService {
+export class DesktopCellEditorService extends RxDisposable implements ICellEditorService {
private _containerElement: HTMLDivElement;
private _editorEngine: Engine;
@@ -69,11 +74,16 @@ export class DesktopCellEditorService extends Disposable implements ICellEditorS
@ICommandService private readonly _commandService: ICommandService,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@IContextService private readonly _contextService: IContextService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ISheetClipboardService private readonly _clipboardService: IClipboardService
) {
super();
this._mountCellEditor();
+
+ // since paste event could only be triggered on an editable element such as textarea / input / contenteditable,
+ // we should bind related event handler to cell editor element
+ this._initPasteHandler();
this._initListeners();
this._focusCurrentSheet();
}
@@ -104,8 +114,7 @@ export class DesktopCellEditorService extends Disposable implements ICellEditorS
const position = this._positionCellEditor(currentCell);
await this._updateDocumentModelFromCellModel(position);
- this._contextService.setContextValue(FOCUSING_SHEET_EDITOR, true);
- this._contextService.setContextValue(FOCUSING_SHEET_CELL_EDITOR, true);
+ this._contextService.setContextValue(SHEET_EDITOR_ACTIVATED, true);
this._currentUniverService.focusUniverInstance(SHEET_CELL_EDITOR_MODEL_ID); // focus the UniverDoc instance to enable rich text editing
this._getCellEditor()?.activate();
@@ -122,8 +131,7 @@ export class DesktopCellEditorService extends Disposable implements ICellEditorS
const currentUniverSheet = this._currentUniverService.getCurrentUniverSheetInstance();
const workbookId = currentUniverSheet.getUnitId();
this._currentUniverService.focusUniverInstance(workbookId);
- this._contextService.setContextValue(FOCUSING_SHEET_EDITOR, false);
- this._contextService.setContextValue(FOCUSING_SHEET_CELL_EDITOR, false);
+ this._contextService.setContextValue(SHEET_EDITOR_ACTIVATED, false);
const model = this._currentUniverService.getUniverDocInstance(SHEET_CELL_EDITOR_MODEL_ID)!.getDocument();
const dataStream = model.getBodyModel().getText();
@@ -204,6 +212,20 @@ export class DesktopCellEditorService extends Disposable implements ICellEditorS
engine.setContainer(this._containerElement);
}
+ private _initPasteHandler(): void {
+ this._enableEditor();
+
+ const editor = this._getCellEditor();
+ if (!editor) {
+ throw new Error('[DesktopCellEditorService]: Could not init paste handler, cell editor not found!');
+ }
+
+ editor.onPaste$.pipe(takeUntil(this.dispose$)).subscribe((e: ClipboardEvent) => {
+ console.log('paste event', e);
+ // TODO: handle paste event from the editor input element
+ });
+ }
+
private _positionCellEditor(currentCell: ISelectionCell) {
const cellInfo = this._selectionTransformerShapeManager.convertCellRangeToInfo(currentCell)!;
@@ -267,13 +289,12 @@ export class DesktopCellEditorService extends Disposable implements ICellEditorS
const cellEditorModel = this._currentUniverService
.getUniverDocInstance(SHEET_CELL_EDITOR_MODEL_ID)
?.getDocument();
+
if (!cellEditorModel) {
throw new Error('Cell editor model not found!');
}
const cellValue = this._getCellValue();
- const style = this._getCellStyle();
-
const snapshot: IDocumentData = {
id: SHEET_CELL_EDITOR_MODEL_ID,
body: {
@@ -286,7 +307,6 @@ export class DesktopCellEditorService extends Disposable implements ICellEditorS
marginBottom: 2,
marginHeader: 2,
marginFooter: 2,
- // FIXME: width here is not correct
pageSize: {
height: (position?.minHeight || 0) - 2 * 2,
width: (position?.minWidth || 0) - 2 * 2,
@@ -323,6 +343,14 @@ export class DesktopCellEditorService extends Disposable implements ICellEditorS
return this._getActiveRange()?.getTextStyle();
}
+ private _enableEditor(): void {
+ return this._injector
+ .get(DocsViewManagerService)
+ .getDocsView(SHEET_CELL_EDITOR_MODEL_ID)
+ ?.getDocs()
+ .enableEditor();
+ }
+
private _getCellEditor(): Nullable<DocsEditor> {
return this._injector
.get(DocsViewManagerService)
diff --git a/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
index e5d2da856c..1156d47b24 100644
--- a/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
+++ b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
@@ -1,46 +1,124 @@
-import { SelectionManagerService } from '@univerjs/base-sheets';
-import { IClipboardInterfaceService } from '@univerjs/base-ui';
-import { Disposable, ICellData, ICurrentUniverService, ILogService, ObjectMatrix, toDisposable } from '@univerjs/core';
+import { ISetRangeValuesMutationParams, SelectionManagerService, SetRangeValuesMutation } from '@univerjs/base-sheets';
+import {
+ HTML_CLIPBOARD_MIME_TYPE,
+ IClipboardInterfaceService,
+ PLAIN_TEXT_CLIPBOARD_MIME_TYPE,
+} from '@univerjs/base-ui';
+import {
+ Disposable,
+ ICellData,
+ ICommandInfo,
+ ICommandService,
+ ICurrentUniverService,
+ ILogService,
+ ISelectionRange,
+ IUndoRedoService,
+ ObjectMatrix,
+ ObjectMatrixPrimitiveType,
+ toDisposable,
+} from '@univerjs/core';
import { createIdentifier, IDisposable, Inject } from '@wendellhu/redi';
+export type ICellDataWithSpanInfo = ICellData & { rowSpan?: number; colSpan?: number };
+
export interface IClipboardPropertyItem {
[key: string]: string;
}
+export interface IParsedCellValue {
+ rowSpan?: number;
+ colSpan?: number;
+ properties: IClipboardPropertyItem;
+ content: string;
+}
+
/**
- * ClipboardHook could:
+ * `ClipboardHook` could:
* 1. Before copy/cut/paste, decide whether to execute the command and prepare caches if necessary.
* 1. When copying, decide what content could be written into clipboard.
* 1. When pasting, get access to the clipboard content and append mutations to the paste command.
*/
export interface ISheetClipboardHook {
- onBeforeCopy?(): void;
- onBeforeCut?(): void;
- onBeforePaste?(): void;
-
- onGetContent(row: number, col: number): string;
+ priority?: number;
+ /**
+ * The callback would be called after the clipboard service has decided what region need to be copied.
+ * Features could use this hook to build copying cache or any other pre-copy jobs.
+ */
+ onBeforeCopy?(workbookId: string, worksheetId: string, range: ISelectionRange): void;
+ /**
+ *
+ * @param row
+ * @param col
+ * @return content
+ */
+ onCopyCellContent?(row: number, col: number): string;
/**
* Properties that would be appended to the td element.
* @param row row of the the copied cell
* @param col col of the the copied cell
*/
- onCopy?(row: number, col: number, rowSpan?: number, colSpan?: number): IClipboardPropertyItem | null;
- onCut?(row: number, col: number): IClipboardPropertyItem | null;
- onPaste?(row: number, col: number): void;
-
+ onCopyCellStyle?(row: number, col: number, rowSpan?: number, colSpan?: number): IClipboardPropertyItem | null;
+ /**
+ * Properties that would be appended to the tr element.
+ * @param row each row of the the copied range
+ */
onCopyRow?(row: number): IClipboardPropertyItem | null;
- onCutRow?(row: number): IClipboardPropertyItem | null;
- onPasteRow?(row: number): void;
-
+ /**
+ * Properties that would be appended to the col element.
+ * @param col each col of the copied range
+ */
onCopyColumn?(col: number): IClipboardPropertyItem | null;
- onCutColumn?(row: number): IClipboardPropertyItem | null;
- onPasteColumn?(row: number): void;
-
+ /**
+ * Would be called after copy content has been written into clipboard.
+ * Features could do some cleaning up jobs here.
+ */
onAfterCopy?(): void;
- onAfterCut?(): void;
- onAfterPaste?(): void;
+ // We do not need cut hooks. We could just use copy hooks to do the same thing,
+ // and tell paste hooks that the source is from a cut command.
+
+ // Unlike copy hooks, paste hooks would be called **only once each** because features would do batch mutations.
+
+ /**
+ * The callback would be called after the clipboard service has decided what region need to be pasted.
+ * Features could use this hook to build copying cache or any other pre-copy jobs.
+ *
+ * @returns if it block copying it should return false
+ */
+ onBeforePaste?(workbookId: string, worksheetId: string, range: ISelectionRange): boolean;
+ /**
+ *
+ * @param row
+ * @param col
+ */
+ onPasteCells?(
+ range: ISelectionRange,
+ matrix: ObjectMatrix<IParsedCellValue>
+ ): {
+ undos: ICommandInfo[];
+ redos: ICommandInfo[];
+ };
+ onPasteRows?(
+ range: ISelectionRange,
+ rowProperties: IClipboardPropertyItem[]
+ ): {
+ undos: ICommandInfo[];
+ redos: ICommandInfo[];
+ };
+ onPasteColumns?(
+ range: ISelectionRange,
+ colProperties: IClipboardPropertyItem[]
+ ): {
+ undos: ICommandInfo[];
+ redos: ICommandInfo[];
+ };
+ onAfterPaste?(success: boolean): void;
+
+ /**
+ * The callback would be called before the clipboard service decides what region need to be copied from or pasted to.
+ * It would jump over these filtered rows when copying or pasting.
+ */
getFilteredOutRows?(): number[];
}
@@ -50,7 +128,7 @@ export interface ISheetClipboardHook {
export interface ISheetClipboardService {
copy(): Promise<boolean>;
cut(): Promise<boolean>;
- paste(): Promise<boolean>;
+ paste(item: ClipboardItem): Promise<boolean>;
addClipboardHook(hook: ISheetClipboardHook): IDisposable;
}
@@ -64,7 +142,9 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
@ILogService private readonly _logService: ILogService,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService
+ @IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,
+ @IUndoRedoService private readonly _undoRedoService: IUndoRedoService,
+ @ICommandService private readonly _commandService: ICommandService
) {
super();
}
@@ -86,14 +166,15 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// 3. calculate selection matrix, span cells would only - maybe warn uses that cells are too may in the future
const { startColumn, startRow, endColumn, endRow } = selection.rangeData;
- const worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const worksheet = workbook.getActiveSheet();
const matrix = worksheet.getMatrixWithMergedCells(startRow, startColumn, endRow, endColumn);
// 4. use filteredRows into to remove rows for the matrix
// TODO: filtering
// tell hooks to get ready for copying
- hooks.forEach((h) => h.onBeforeCopy?.());
+ hooks.forEach((h) => h.onBeforeCopy?.(workbook.getUnitId(), worksheet.getSheetId(), selection.rangeData));
// 5. generate html and pure text contents by calling all clipboard hooks
// col styles
@@ -104,13 +185,14 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// TODO: cols here should filtered out those in span cells
rowContents.push(getRowContent(row, cols, hooks, matrix));
});
- // final result
- const html = `<google-sheets-html-origin><style type="text/css"><!--td {border: 1px solid #cccccc;}br {mso-data-placement:same-cell;}--></style><table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" border="1" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none">${colStyles}<tbody>${rowContents.join(
- ''
- )}</tbody></table>`;
- // 6. write html and maybe plain text info the clipboard interface
- await this._clipboardInterfaceService.write('table', html);
+ const html = `<google-sheets-html-origin><style type="text/css"><!--td {border: 1px solid #cccccc;}br {mso-data-placement:same-cell;}--></style>
+<table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" border="1" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none">${colStyles}
+<tbody>${rowContents.join('')}</tbody></table>`;
+
+ // TODO: plain text copying is not implemented yet
+ // 6. write html and get plain text info the clipboard interface
+ await this._clipboardInterfaceService.write('TODO: plain text copy is not implemented', html);
// tell hooks to clean up
hooks.forEach((h) => h.onAfterCopy?.());
@@ -119,16 +201,36 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
async cut(): Promise<boolean> {
+ // TODO: pretty the same as `copy` but we should mark the cutting area and highlight it with a selection
return true;
}
- async paste(): Promise<boolean> {
- return true;
+ async paste(item: ClipboardItem): Promise<boolean> {
+ const types = item.types;
+ const text =
+ types.indexOf(PLAIN_TEXT_CLIPBOARD_MIME_TYPE) !== -1
+ ? await item.getType(PLAIN_TEXT_CLIPBOARD_MIME_TYPE).then((blob) => blob.text())
+ : '';
+ const html =
+ types.indexOf(HTML_CLIPBOARD_MIME_TYPE) !== -1
+ ? await item.getType(HTML_CLIPBOARD_MIME_TYPE).then((blob) => blob.text())
+ : '';
+
+ if (html && isLegalSpreadsheetHTMLContent(html)) {
+ // Firstly see if the html content is in good format.
+ // In another word, if it is copied from any spreadsheet apps (including Univer itself).
+ return this._pasteHTML(html);
+ }
+
+ if (text) {
+ return this._pastePlainText(text);
+ }
+
+ return false;
}
addClipboardHook(hook: ISheetClipboardHook): IDisposable {
this._clipboardHooks.push(hook);
-
return toDisposable(() => {
const index = this._clipboardHooks.indexOf(hook);
if (index > -1) {
@@ -137,20 +239,298 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
});
}
- getCellContentClipboardHooks(): Readonly<ISheetClipboardHook[]> {
- return this._clipboardHooks.slice();
+ private async _pastePlainText(text: string): Promise<boolean> {
+ // this._logService.log('[SheetClipboardService]', 'pasting plain text content.', text);
+
+ // TODO: maybe we should support pasting rich text values here? That is not supported yet.
+ const target = this._getPastingTarget();
+ if (!target.selection) {
+ return false;
+ }
+
+ const rangeData = target.selection.rangeData;
+ const cellValue: ObjectMatrixPrimitiveType<ICellData> = {
+ [rangeData.startRow]: {
+ [rangeData.endColumn]: {
+ v: text,
+ },
+ },
+ };
+
+ const setRangeValuesParams: ISetRangeValuesMutationParams = {
+ workbookId: target.workbookId,
+ worksheetId: target.worksheetId,
+ rangeData: [target.selection.rangeData],
+ cellValue,
+ };
+
+ const result = this._commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesParams);
+ return result;
+ }
+
+ private async _pasteHTML(html: string): Promise<boolean> {
+ // this._logService.log('[SheetClipboardService]', 'pasting html content', html);
+
+ // TODO: support internal pasting
+ if (true) {
+ return this._pasteExternal(html);
+ }
+
+ return this._pasteInternal();
+ }
+
+ private async _pasteExternal(html: string): Promise<boolean> {
+ // this._logService.log('[SheetClipboardService]', 'pasting external content', html);
+
+ // steps of pasting:
+ const target = this._getPastingTarget();
+ const { selection, workbookId, worksheetId } = target;
+ if (!selection) {
+ return false;
+ }
+
+ // 1. get properties of the table by parsing raw html content, including col properties / row properties
+ // cell properties and cell contents.
+ const colProperties = parseColGroup(html);
+ const { rowProperties, rowCount, colCount, cellMatrix } = parseTableRows(html);
+ if (!cellMatrix) {
+ return false;
+ }
+
+ // 2. get filtered rows in the target pasting area and get the final pasting matrix
+ // we also handle transpose pasting at this step
+ // note: handle transpose before filtering
+ // matrix before adjustment -> transpose -> filtering -> matrix under adjustment
+ // TODO: not implemented yet
+
+ // 3. call hooks with cell position and properties and get mutations (both do mutations and undo mutations)
+ // we also handle 'copy value only' or 'copy style only' as this step
+ const pastedRange = { ...selection.rangeData };
+ pastedRange.endColumn = pastedRange.startColumn + colCount;
+ pastedRange.endRow = pastedRange.startRow + rowCount;
+ const hooks = this._clipboardHooks;
+ const enabledHooks: ISheetClipboardHook[] = [];
+ const disableCopying = hooks.some(
+ (h) => enabledHooks.push(h) && h.onBeforePaste?.(workbookId, worksheetId, pastedRange) === false
+ );
+ if (disableCopying) {
+ enabledHooks.forEach((h) => h.onAfterPaste?.(false));
+ return false;
+ }
+
+ const redoMutationsInfo: ICommandInfo[] = [];
+ const undoMutationsInfo: ICommandInfo[] = [];
+
+ hooks.forEach((h) => {
+ const rowReturn = h.onPasteRows?.(pastedRange, rowProperties);
+ if (rowReturn) {
+ redoMutationsInfo.push(...rowReturn.redos);
+ undoMutationsInfo.push(...rowReturn.undos);
+ }
+
+ const colReturn = h.onPasteColumns?.(pastedRange, colProperties || new Array(colCount).map(() => ({})));
+ if (colReturn) {
+ redoMutationsInfo.push(...colReturn.redos);
+ undoMutationsInfo.push(...colReturn.undos);
+ }
+
+ const contentReturn = h.onPasteCells?.(pastedRange, cellMatrix);
+ if (contentReturn) {
+ redoMutationsInfo.push(...contentReturn.redos);
+ undoMutationsInfo.push(...contentReturn.undos);
+ }
+ });
+
+ // 4. execute these mutations
+ this._logService.log('[SheetClipboardService]', 'pasting mutations', {
+ undoMutationsInfo,
+ redoMutationsInfo,
+ });
+
+ const result = redoMutationsInfo.every((m) => this._commandService.executeCommand(m.id, m.params));
+ if (result) {
+ // add to undo redo services
+ }
+
+ return result;
+ }
+
+ private async _pasteInternal(): Promise<boolean> {
+ // internal pasting is pretty much like `_pasteExternal`
+ return true;
+ // NOTE: if the source is from a cut command, we should invoke a move mutation instead
+ }
+
+ // NOTE: why there are some differences between internal and external pasting?
+
+ private _getPastingTarget() {
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const worksheet = workbook.getActiveSheet();
+ const selection = this._selectionManagerService.getLast();
+ return {
+ workbookId: workbook.getUnitId(),
+ worksheetId: worksheet.getSheetId(),
+ selection,
+ };
+ }
+}
+
+// #region paste parsing
+
+/**
+ * Parse columns and their properties from colgroup element.
+ *
+ * @param raw content
+ * @returns cols and their properties
+ */
+function parseColGroup(raw: string): IClipboardPropertyItem[] | null {
+ const COLGROUP_TAG_REGEX = /<colgroup([\s\S]*?)>(.*?)<\/colgroup>/;
+ const colgroupMatch = raw.match(COLGROUP_TAG_REGEX);
+ if (!colgroupMatch || !colgroupMatch[2]) {
+ return null;
+ }
+
+ const COL_TAG_REGEX = /<col([\s\S]*?)>/g;
+ const colMatches = colgroupMatch[2].matchAll(COL_TAG_REGEX);
+ if (!colMatches) {
+ return null;
+ }
+
+ return Array.from(colMatches).map((colMatch) => parseProperties(colMatch[1]));
+}
+
+/**
+ * This function parses <tr> elements in the table. So it would return several things.
+ * @param html raw content
+ * @returns
+ */
+function parseTableRows(html: string): {
+ rowProperties: IClipboardPropertyItem[];
+ rowCount: number;
+ colCount: number;
+ cellMatrix: ObjectMatrix<IParsedCellValue> | null;
+} {
+ const ROWS_REGEX = /<tr([\s\S]*?)>([\s\S]*?)<\/tr>/gi;
+ const rowMatches = html.matchAll(ROWS_REGEX);
+ if (!rowMatches) {
+ return {
+ rowProperties: [],
+ rowCount: 0,
+ colCount: 0,
+ cellMatrix: null,
+ };
+ }
+
+ const rowMatchesAsArray = Array.from(rowMatches);
+ const rowProperties = rowMatchesAsArray.map((rowMatch) => parseProperties(rowMatch[1]));
+
+ const { colCount, cellMatrix } = parseTableCells(rowMatchesAsArray.map((rowMatch) => rowMatch[2]));
+
+ return {
+ rowProperties,
+ rowCount: rowProperties.length,
+ colCount,
+ cellMatrix,
+ };
+}
+
+/**
+ *
+ * @param tdStrings
+ */
+function parseTableCells(tdStrings: string[]) {
+ const cellMatrix = new ObjectMatrix<IParsedCellValue>();
+ const maxRowOfCol = new Map<number, number>();
+ const TDS_REGEX = /<td([\s\S]*?)>([\s\S]*?)<\/td>/gi;
+
+ let colCount = 0;
+ let colIndex = 0;
+ let rowIndex = 0;
+
+ tdStrings.forEach((trStr, r) => {
+ const isFirstRow = r === 0;
+ const cellMatches = trStr.matchAll(TDS_REGEX);
+
+ colIndex = 0;
+
+ Array.from(cellMatches).forEach((cellMatch) => {
+ const cellProperties = parseProperties(cellMatch[1]);
+ const content = cellMatch[2];
+ const rowSpan = cellProperties.rowspan ? +cellProperties.rowspan : 1;
+ const colSpan = cellProperties.colspan ? +cellProperties.colspan : 1;
+
+ if (!isFirstRow) {
+ for (let i = colIndex; i < colCount; i++) {
+ const thisPosOccupied = maxRowOfCol.get(i)! >= rowIndex;
+ if (!thisPosOccupied) {
+ colIndex = i;
+ break;
+ }
+ }
+ }
+
+ const value: IParsedCellValue = {
+ content,
+ properties: cellProperties,
+ };
+ if (colSpan > 1) value.colSpan = +colSpan;
+ if (rowSpan > 1) value.rowSpan = +rowSpan;
+
+ // when iterating the first row, we should calc colCount as well
+ if (isFirstRow) {
+ colCount += colSpan;
+ }
+
+ // update maxRowOfCol
+ for (let i = colIndex; i < colIndex + colSpan; i++) {
+ maxRowOfCol.set(i, rowIndex + rowSpan - 1);
+ }
+
+ // set value to matrix
+ cellMatrix.setValue(rowIndex, colIndex, value);
+
+ // point to next colIndex
+ colIndex += colSpan;
+ });
+
+ rowIndex += 1;
+ });
+
+ return {
+ colCount,
+ cellMatrix,
+ };
+}
+
+function parseProperties(propertyStr: string): IClipboardPropertyItem {
+ if (!propertyStr) {
+ return {};
}
+
+ const PROPERTY_REGEX = /([\w-]+)="([^"]*)"/gi;
+ const propertyMatches = propertyStr.matchAll(PROPERTY_REGEX);
+ const property: IClipboardPropertyItem = {};
+ Array.from(propertyMatches).forEach((m) => {
+ const [_, key, val] = m;
+ property[key] = val;
+ });
+
+ return property;
}
+// #endregion
+
+// #region copy generation
+
/**
*
* @param matrix
* @param cols
* @param hooks
*/
-export function getTableContent(matrix: number[][], cols: number[], hooks: ISheetClipboardHook[]) {}
+function getTableContent(matrix: number[][], cols: number[], hooks: ISheetClipboardHook[]) {}
-export function getSingleCellContent() {}
+function getSingleCellContent() {}
/**
* Get content of a single td element.
@@ -162,15 +542,15 @@ function getTDContent(
row: number,
col: number,
hooks: ISheetClipboardHook[],
- matrix: ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }>
+ matrix: ObjectMatrix<ICellDataWithSpanInfo>
) {
const v = matrix.getValue(row, col);
const properties = hooks
- .map((hook) => hook.onCopy?.(row, col, v?.rowSpan, v?.colSpan))
+ .map((hook) => hook.onCopyCellStyle?.(row, col, v?.rowSpan, v?.colSpan))
.filter((v) => !!v) as IClipboardPropertyItem[];
const mergedProperties = mergeProperties(properties);
const str = zipClipboardPropertyItemToString(mergedProperties);
- const content = hooks.reduce((acc, hook) => acc || hook.onGetContent?.(row, col) || '', '');
+ const content = hooks.reduce((acc, hook) => acc || hook.onCopyCellContent?.(row, col) || '', '');
return `<td${str}>${content}</td>`;
}
@@ -185,7 +565,7 @@ function getRowContent(
row: number,
cols: number[],
hooks: ISheetClipboardHook[],
- matrix: ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }>
+ matrix: ObjectMatrix<ICellDataWithSpanInfo>
) {
const properties = hooks.map((hook) => hook.onCopyRow?.(row)).filter((v) => !!v) as IClipboardPropertyItem[];
const mergedProperties = mergeProperties(properties);
@@ -241,3 +621,9 @@ function getArrayFromTo(f: number, to: number): number[] {
}
return arr;
}
+
+function isLegalSpreadsheetHTMLContent(html: string): boolean {
+ return html.indexOf('<table') !== -1; // NOTE: This is just a temporary implementation. Definitely would be changed later.
+}
+
+// #endregion
diff --git a/packages/ui-plugin-sheets/src/services/clipboard/test/clipboard.service.spec.ts b/packages/ui-plugin-sheets/src/services/clipboard/test/clipboard.service.spec.ts
new file mode 100644
index 0000000000..52082304a5
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/services/clipboard/test/clipboard.service.spec.ts
@@ -0,0 +1 @@
+describe('Test clipboard content parsing algorithms', () => {});
diff --git a/packages/ui-plugin-sheets/src/services/context/context.ts b/packages/ui-plugin-sheets/src/services/context/context.ts
index ac19d86f17..cadb605d59 100644
--- a/packages/ui-plugin-sheets/src/services/context/context.ts
+++ b/packages/ui-plugin-sheets/src/services/context/context.ts
@@ -1,2 +1,7 @@
-export const FOCUSING_SHEET_CELL_EDITOR = 'FOCUSING_SHEET_CELL_EDITOR';
-export const FOCUSING_SHEET_EDITOR = 'FOCUSING_SHEET_EDITOR';
+/**
+ * The situation where sheet editor is activated (cursor blinking).
+ *
+ * Note tha sheet cell editor is always focused when a UniverSheet instance is focused (and other input element
+ * is not `document.activeElement`).
+ */
+export const SHEET_EDITOR_ACTIVATED = 'SHEET_EDITOR_ACTIVATED';
diff --git a/packages/ui-plugin-sheets/src/services/shortcuts/shortcuts.ts b/packages/ui-plugin-sheets/src/services/shortcuts/shortcuts.ts
index c5e2f41892..723aebe142 100644
--- a/packages/ui-plugin-sheets/src/services/shortcuts/shortcuts.ts
+++ b/packages/ui-plugin-sheets/src/services/shortcuts/shortcuts.ts
@@ -1,10 +1,10 @@
import { IShortcutItem, KeyCode } from '@univerjs/base-ui';
import { QuitCellEditorCommand } from '../cell-editor/cell-editor.command';
-import { FOCUSING_SHEET_CELL_EDITOR } from '../context/context';
+import { SHEET_EDITOR_ACTIVATED } from '../context/context';
export const QuitCellEditorShortcutItem: IShortcutItem = {
id: QuitCellEditorCommand.id,
binding: KeyCode.ENTER,
- preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),
+ preconditions: (contextService) => contextService.getContextValue(SHEET_EDITOR_ACTIVATED),
};
diff --git a/packages/ui-plugin-slides/src/Controller/SlideContainerUIController.ts b/packages/ui-plugin-slides/src/Controller/SlideContainerUIController.ts
index 422645518a..b82d06c091 100644
--- a/packages/ui-plugin-slides/src/Controller/SlideContainerUIController.ts
+++ b/packages/ui-plugin-slides/src/Controller/SlideContainerUIController.ts
@@ -29,7 +29,10 @@ export class SlideContainerUIController {
@Inject(DragManager) private readonly _dragManager: DragManager
) {
this._config = config;
- this._toolbarController = this._injector.createInstance(ToolbarUIController, this._config.layout?.toolbarConfig);
+ this._toolbarController = this._injector.createInstance(
+ ToolbarUIController,
+ this._config.layout?.toolbarConfig
+ );
this._infoBarController = this._injector.createInstance(InfoBarUIController);
this._slideBarController = this._injector.createInstance(SlideBarUIController);
// this._dragManager = this._injector.createInstance(DragManager);