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): basic copying styles (#161)

Wenzhao Hudb60e50d9c91
diff --git a/.nvmrc b/.nvmrc
index 3b3a53bf3c..39d00c0517 100644
--- a/.nvmrc
+++ b/.nvmrc
@@ -1 +1 @@
-16.20.0
\ No newline at end of file
+18.17.0
\ No newline at end of file
diff --git a/package.json b/package.json
index 562eb647ac..2d0ee379f4 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,7 @@
"lint:fix": "eslint packages/**/src/**/*.{tsx,ts} --fix"
},
"engines": {
- "node": "^16.20.0",
+ "node": "^18.17.0",
"pnpm": "^8.6.2"
},
"author": "DreamNum <[email protected]>",
diff --git a/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts b/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts
index 87d7eac321..1377d5e5e4 100644
--- a/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts
@@ -14,7 +14,11 @@ import {
import { IAccessor } from '@wendellhu/redi';
import { SelectionManagerService } from '../../Services/selection-manager.service';
-import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';
+import {
+ ISetRangeValuesMutationParams,
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+} from '../Mutations/set-range-values.mutation';
export interface ISetRangeValuesCommandParams {
worksheetId?: string;
@@ -39,7 +43,11 @@ export const SetRangeValuesCommand: ICommand = {
value,
range,
workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId(),
- worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId(),
+ worksheetId = currentUniverService
+ .getCurrentUniverSheetInstance()
+ .getWorkBook()
+ .getActiveSheet()
+ .getSheetId(),
} = params;
const currentSelections = range ? [range] : selectionManagerService.getRangeDatas();
@@ -72,7 +80,10 @@ export const SetRangeValuesCommand: ICommand = {
workbookId,
cellValue: realCellValue ?? cellValue.getMatrix(),
};
- const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, setRangeValuesMutationParams);
+ const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ setRangeValuesMutationParams
+ );
const result = commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutationParams);
if (result) {
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 55310de3ce..4349835ad8 100644
--- a/packages/base-ui/src/services/clipboard/clipboard-interface.service.ts
+++ b/packages/base-ui/src/services/clipboard/clipboard-interface.service.ts
@@ -32,16 +32,22 @@ export interface IClipboardInterfaceService {
// NOTE: maybe we should add an interface to support image copy
}
-export const IClipboardInterfaceService = createIdentifier<IClipboardInterfaceService>('univer.clipboard-interface-service');
+export const IClipboardInterfaceService = createIdentifier<IClipboardInterfaceService>(
+ 'univer.clipboard-interface-service'
+);
export class BrowserClipboardService extends Disposable implements IClipboardInterfaceService {
async write(text: string, html: string): Promise<void> {
- // try {
- // // write both pure text content and html content to the clipboard
- // return await navigator.clipboard.write();
- // } catch (error) {
- // console.error(error);
- // }
+ try {
+ // 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' }),
+ }),
+ ]);
+ } catch (error) {
+ console.error(error);
+ }
}
async writeText(text: string): Promise<void> {
diff --git a/packages/core/src/Shared/ObjectArray.ts b/packages/core/src/Shared/ObjectArray.ts
index c7bc92cd53..2a946eb034 100644
--- a/packages/core/src/Shared/ObjectArray.ts
+++ b/packages/core/src/Shared/ObjectArray.ts
@@ -273,10 +273,32 @@ export class ObjectArray<T> {
return keys.length === 0;
}
+ /**
+ * @deprecated use `realDelete` or `splice`
+ * @param index
+ */
delete(index: number): void {
this.splice(index, 1);
}
+ realDelete(index: number): void {
+ const length = this._length;
+ if (length > 0) {
+ const end = index + 1;
+ const array = this._array;
+ let effective = 0;
+ const splice: ObjectArrayPrimitiveType<T> = {};
+ for (let i = index; i < end; i++) {
+ const item = array[i];
+ if (define(item)) {
+ delete array[i];
+ splice[effective] = item;
+ effective++;
+ }
+ }
+ }
+ }
+
includes(target: T): boolean {
const array = this._array;
const keys = Object.keys(array);
diff --git a/packages/core/src/Shared/ObjectMatrix.ts b/packages/core/src/Shared/ObjectMatrix.ts
index c17dcf9c33..3b14029941 100644
--- a/packages/core/src/Shared/ObjectMatrix.ts
+++ b/packages/core/src/Shared/ObjectMatrix.ts
@@ -48,6 +48,21 @@ export class ObjectMatrix<T> {
return this;
}
+ forRow(callback: (row: number, cols: number[]) => Nullable<boolean>): void {
+ const keys = this._option.getKeys();
+ for (let i = 0; i < keys.length; i++) {
+ const key = +keys[i];
+ const value = this.getRow(key) as ObjectArray<T>;
+ const result = callback(
+ key,
+ value.getKeys().map((item) => +item)
+ );
+ if (result === false) {
+ return;
+ }
+ }
+ }
+
forValue(callback: (row: number, col: number, value: T) => Nullable<boolean>): ObjectMatrix<T> {
const keys = this._option.getKeys();
for (let i = 0; i < keys.length; i++) {
@@ -125,6 +140,13 @@ export class ObjectMatrix<T> {
}
}
+ realDeleteValue(row: number, column: number): void {
+ const objectArray = this.getRow(row);
+ if (objectArray) {
+ objectArray.realDelete(column);
+ }
+ }
+
spliceRows(start: number, count: number): ObjectMatrix<T> {
const splice = this._option.splice(start, count);
return new ObjectMatrix(splice.toJSON() as ObjectMatrixPrimitiveType<T>);
diff --git a/packages/core/src/Sheets/Domain/Worksheet.ts b/packages/core/src/Sheets/Domain/Worksheet.ts
index 4ef16321b3..2a1d467dca 100644
--- a/packages/core/src/Sheets/Domain/Worksheet.ts
+++ b/packages/core/src/Sheets/Domain/Worksheet.ts
@@ -3,6 +3,7 @@ import { Inject } from '@wendellhu/redi';
import { ObserverManager } from '../../Observer';
import { ICurrentUniverService } from '../../services/current.service';
import { Nullable, ObjectMatrix, Rectangle, Tools } from '../../Shared';
+import { createRowColIter } from '../../Shared/RowColIter';
import { DEFAULT_WORKSHEET } from '../../Types/Const';
import { BooleanNumber, SheetTypes } from '../../Types/Enum';
import { ICellData, IRangeData, IRangeStringData, IRangeType, IWorksheetConfig } from '../../Types/Interfaces';
@@ -144,9 +145,48 @@ export class Worksheet {
/**
* Get cell matrix from a given range and pick out non-first cells of merged cells.
*/
- getMatrixWithMergedCells(row: number, col: number, endRow: number, endCol: number): ObjectMatrix<ICellData> {
- // TODO@wzhudev: implement this method
- // const mergedCellsInRange = this.
+ // PERF: we could not skip indexes with merged cells, because we have already known the merged cells' range
+ getMatrixWithMergedCells(
+ row: number,
+ col: number,
+ endRow: number,
+ endCol: number
+ ): ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }> {
+ const matrix = this.getCellMatrix();
+ const mergedCellsInRange = this._snapshot.mergeData.filter((rect) => {
+ const rectRange = new Rectangle(rect);
+ const targetRange = new Rectangle(row, col, endRow, endCol);
+ return rectRange.intersects(targetRange);
+ });
+
+ const ret = new ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }>();
+
+ createRowColIter(row, endRow, col, endCol).forEach((row, col) => {
+ const v = matrix.getValue(row, col);
+ if (v) {
+ // ICellData should combine merge info
+ ret.setValue(row, col, v);
+ }
+ });
+
+ mergedCellsInRange.forEach((mergedCell) => {
+ const { startColumn, startRow, endColumn, endRow } = mergedCell;
+ createRowColIter(startRow, endRow, startColumn, endColumn).forEach((row, col) => {
+ if (row === startRow && col === startColumn) {
+ ret.setValue(row, col, {
+ ...ret.getValue(row, col),
+ rowSpan: endRow - startRow + 1,
+ colSpan: endColumn - startColumn + 1,
+ });
+ }
+
+ if (row !== startRow || col !== startColumn) {
+ ret.realDeleteValue(row, col);
+ }
+ });
+ });
+
+ return ret;
}
// WTF: this function signature is so ridiculous...
diff --git a/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts b/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
index 77e6a4cd7f..34ece15c25 100644
--- a/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
@@ -1,5 +1,12 @@
import { CanvasView } from '@univerjs/base-sheets';
-import { BaseMenuItem, BaseSelectChildrenProps, ComponentManager, IMenuItemFactory, IMenuService, MenuPosition } from '@univerjs/base-ui';
+import {
+ BaseMenuItem,
+ BaseSelectChildrenProps,
+ ComponentManager,
+ IMenuItemFactory,
+ IMenuService,
+ MenuPosition,
+} from '@univerjs/base-ui';
import { Disposable } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
@@ -7,6 +14,7 @@ import { SheetRightMenuConfig } from '../Basics';
import { RightMenu, RightMenuInput, RightMenuItem } from '../View';
import {
ClearSelectionMenuItemFactory,
+ CopyMenuItemFactory,
DeleteRangeMenuItemFactory,
DeleteRangeMoveLeftMenuItemFactory,
DeleteRangeMoveUpMenuItemFactory,
@@ -89,6 +97,7 @@ export class RightMenuUIController extends Disposable {
(
[
+ CopyMenuItemFactory,
ClearSelectionMenuItemFactory,
InsertRowMenuItemFactory,
InsertColMenuItemFactory,
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 5e6de367c6..fd23a048bd 100644
--- a/packages/ui-plugin-sheets/src/Controller/clipboard/clipboard.controller.ts
+++ b/packages/ui-plugin-sheets/src/Controller/clipboard/clipboard.controller.ts
@@ -1,7 +1,11 @@
-import { Disposable, ICommandService, ICurrentUniverService, Worksheet } from '@univerjs/core';
+import { Disposable, ICommandService, ICurrentUniverService, Worksheet, WrapStrategy } from '@univerjs/core';
import { SheetCopyCommand, SheetCutCommand, SheetPasteCommand } from '../../commands/commands/clipboard.command';
-import { ISheetClipboardHook, ISheetClipboardService } from '../../services/clipboard/clipboard.service';
+import {
+ IClipboardPropertyItem,
+ ISheetClipboardHook,
+ ISheetClipboardService,
+} from '../../services/clipboard/clipboard.service';
/**
* This controller add basic clipboard logic for basic features such as text color / BISU / row widths to the clipboard
@@ -30,17 +34,74 @@ export class SheetClipboardController extends Disposable {
// and create necessary cache if needed
currentSheet = self._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
},
- onGetContent(row: number, col: number) {},
- // copy
- onCopy: (row: number, col: number) => ({
- 'data-row': row.toString(),
- 'data-col': col.toString(),
- }),
+ onGetContent(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
+ const properties: IClipboardPropertyItem = {};
+
+ if (rowSpan) {
+ properties.rowspan = `${rowSpan}`;
+ }
+ if (colSpan) {
+ properties.colspan = `${colSpan}`;
+ }
+
+ const range = currentSheet!.getRange(row, col);
+ const textStyle = range.getTextStyle();
+ const color = range.getFontColor();
+ const backgroundColor = range.getBackground();
+
+ let style = '';
+ if (color) {
+ style += `color: ${color};`;
+ }
+ if (backgroundColor) {
+ style += `background-color: ${backgroundColor};`;
+ }
+ if (textStyle?.bl) {
+ style += 'font-weight: bold;';
+ }
+ if (textStyle?.fs) {
+ style += `font-size: ${textStyle.fs}px;`;
+ }
+ if (textStyle?.tb === WrapStrategy.WRAP) {
+ style += 'word-wrap: break-word;';
+ }
+ if (textStyle?.it) {
+ style += 'font-style: italic;';
+ }
+ if (textStyle?.ff) {
+ style += `font-family: ${textStyle.ff};`;
+ }
+ if (textStyle?.st) {
+ style += 'text-decoration: line-through;';
+ }
+ if (textStyle?.ul) {
+ style += 'text-decoration: underline';
+ }
+
+ if (style) {
+ properties.style = style;
+ }
+
+ return properties;
+ },
onCopyColumn(col: number) {
- return null;
+ const sheet = currentSheet!;
+ const width = sheet.getColumnWidth(col);
+ return {
+ width: `${width}`,
+ };
},
onCopyRow(row: number) {
- return null;
+ const sheet = currentSheet!;
+ const height = sheet.getRowHeight(row);
+ return {
+ style: `height: ${height}px;`,
+ };
},
onAfterCopy() {
currentSheet = null;
diff --git a/packages/ui-plugin-sheets/src/Controller/menu.ts b/packages/ui-plugin-sheets/src/Controller/menu.ts
index a90c9229f4..5f51be536b 100644
--- a/packages/ui-plugin-sheets/src/Controller/menu.ts
+++ b/packages/ui-plugin-sheets/src/Controller/menu.ts
@@ -32,7 +32,16 @@ import {
SetWorksheetRowHideCommand,
SetWorksheetRowShowCommand,
} from '@univerjs/base-sheets';
-import { ColorPicker, DisplayTypes, IMenuButtonItem, IMenuSelectorItem, MenuItemType, MenuPosition, SelectTypes } from '@univerjs/base-ui';
+import {
+ ColorPicker,
+ CopyCommand,
+ DisplayTypes,
+ IMenuButtonItem,
+ IMenuSelectorItem,
+ MenuItemType,
+ MenuPosition,
+ SelectTypes,
+} from '@univerjs/base-ui';
import {
FontItalic,
FontWeight,
@@ -883,6 +892,15 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
};
}
+export function CopyMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ return {
+ id: CopyCommand.id,
+ type: MenuItemType.BUTTON,
+ title: 'rightClick.copy',
+ positions: [MenuPosition.CONTEXT_MENU],
+ };
+}
+
export function ClearSelectionMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
return {
id: ClearSelectionContentCommand.id,
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 992c0fd0f8..543367d363 100644
--- a/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
+++ b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
@@ -12,11 +12,8 @@ export const SheetCopyCommand: IMultiCommand = {
priority: 1000,
preconditions: (contextService: IContextService) =>
contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_EDITOR),
- handler: async (accessor, params) => {
+ handler: async (accessor) => {
const sheetClipboardService = accessor.get(ISheetClipboardService);
-
- // TODO: permission control here?
-
return sheetClipboardService.copy();
},
};
diff --git a/packages/ui-plugin-sheets/src/commands/commands/utils/copy-util.ts b/packages/ui-plugin-sheets/src/commands/commands/utils/copy-util.ts
deleted file mode 100644
index 8512fe1bc2..0000000000
--- a/packages/ui-plugin-sheets/src/commands/commands/utils/copy-util.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { IClipboardPropertyItem, ISheetClipboardHook } from '../../../services/clipboard/clipboard.service';
-
-/**
- *
- * @param matrix
- * @param cols
- * @param hooks
- */
-export function getTableContent(matrix: number[][], cols: number[], hooks: ISheetClipboardHook[]) {}
-
-export function getSingleCellContent() {}
-
-/**
- * Get content of a single td element.
- * @param row index of the copied cell
- * @param col index of the copied cell
- * @returns
- */
-function getTDContent(row: number, col: number, content: string, hooks: ISheetClipboardHook[]) {
- const properties = hooks.map((hook) => hook.onCopy?.(row, col)).filter((v) => !v) as IClipboardPropertyItem[];
- const mergedProperties = mergeProperties(properties);
- const str = zipClipboardPropertyItemToString(mergedProperties);
- return `<td ${str}>${content}</td>`;
-}
-
-/**
- *
- * @param row index of the copied row
- * @param cols
- * @param hooks
- * @returns
- */
-function getRowContent(row: number, cols: number[], hooks: ISheetClipboardHook[]) {
- const properties = hooks.map((hook) => hook.onCopyRow?.(row)).filter((v) => !v) as IClipboardPropertyItem[];
- const mergedProperties = mergeProperties(properties);
- const str = zipClipboardPropertyItemToString(mergedProperties);
- // TODO: content is not set
- const tds = cols.map((col) => getTDContent(row, col, '', hooks)).join('');
-
- return `<tr ${str}>${tds}</tr>`;
-}
-
-function getColStyle(cols: number[], hooks: ISheetClipboardHook[]) {
- const str = cols
- .map((col) => {
- const properties = hooks
- .map((hook) => hook.onCopyColumn?.(col))
- .filter((v) => !v) as IClipboardPropertyItem[];
- const mergedProperties = mergeProperties(properties);
- const str = zipClipboardPropertyItemToString(mergedProperties);
- return `<col ${str}>`;
- })
- .join('');
-
- return `<colgroup>${str}</colgroup>`;
-}
-
-function mergeProperties(properties: IClipboardPropertyItem[]): IClipboardPropertyItem {
- return properties.reduce((acc, cur) => {
- const keys = Object.keys(cur);
- keys.forEach((key) => {
- if (!acc[key]) {
- acc[key] = cur[key];
- } else {
- acc[key] += `;${cur[key]}`;
- }
- });
- return acc;
- }, {});
-}
-
-function zipClipboardPropertyItemToString(item: IClipboardPropertyItem) {
- return Object.keys(item).reduce((acc, cur) => {
- acc += `${cur}="${item[cur]}"`;
- return acc;
- }, '');
-}
diff --git a/packages/ui-plugin-sheets/src/commands/commands/utils/test/copy-util.spec.ts b/packages/ui-plugin-sheets/src/commands/commands/utils/test/copy-util.spec.ts
deleted file mode 100644
index e69de29bb2..0000000000
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 9c7b09c774..e5d2da856c 100644
--- a/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
+++ b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
@@ -1,6 +1,6 @@
import { SelectionManagerService } from '@univerjs/base-sheets';
import { IClipboardInterfaceService } from '@univerjs/base-ui';
-import { Disposable, ICurrentUniverService, toDisposable } from '@univerjs/core';
+import { Disposable, ICellData, ICurrentUniverService, ILogService, ObjectMatrix, toDisposable } from '@univerjs/core';
import { createIdentifier, IDisposable, Inject } from '@wendellhu/redi';
export interface IClipboardPropertyItem {
@@ -18,16 +18,16 @@ export interface ISheetClipboardHook {
onBeforeCut?(): void;
onBeforePaste?(): void;
- onGetContent(row: number, col: number): void;
+ onGetContent(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): IClipboardPropertyItem | null;
+ onCopy?(row: number, col: number, rowSpan?: number, colSpan?: number): IClipboardPropertyItem | null;
onCut?(row: number, col: number): IClipboardPropertyItem | null;
- onPaste?(row: number, col: number): void; // TODO: should add raw content here
+ onPaste?(row: number, col: number): void;
onCopyRow?(row: number): IClipboardPropertyItem | null;
onCutRow?(row: number): IClipboardPropertyItem | null;
@@ -61,6 +61,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
private _clipboardHooks: ISheetClipboardHook[] = [];
constructor(
+ @ILogService private readonly _logService: ILogService,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService
@@ -69,16 +70,14 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
async copy(): Promise<boolean> {
- const hooks = this._clipboardHooks;
- // steps to copy cells from the sheet
-
// 1. get the selected range, the range should be the last one of selected ranges
- const selections = this._selectionManagerService.getLast();
- if (!selections) {
+ const selection = this._selectionManagerService.getLast();
+ if (!selection) {
return false; // maybe we should notify user that there is no selection
}
- // 2. filtered out rows those are filtered out by plugins (e.g. filter feature)
+ // 2. get filtered out rows those are filtered out by plugins (e.g. filter feature)
+ const hooks = this._clipboardHooks;
const filteredRows = hooks.reduce((acc, cur) => {
const rows = cur.getFilteredOutRows?.();
rows?.forEach((r) => acc.add(r));
@@ -86,14 +85,35 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}, new Set<number>());
// 3. calculate selection matrix, span cells would only - maybe warn uses that cells are too may in the future
- // TODO: calculate the selection matrix considering about merged cells and filtered out rows
-
- // 4. generate html and pure text contents by calling all clipboard hooks
+ const { startColumn, startRow, endColumn, endRow } = selection.rangeData;
+ const worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().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?.());
+
+ // 5. generate html and pure text contents by calling all clipboard hooks
+ // col styles
+ const colStyles = getColStyle(getArrayFromTo(startColumn, endColumn), hooks);
+ // row styles and table contents
+ const rowContents: string[] = [];
+ matrix.forRow((row, cols) => {
+ // 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>`;
- // 5. write contents to the clipboard interface and done!
- // await this._clipboardInterfaceService.write();
+ // 6. write html and maybe plain text info the clipboard interface
+ await this._clipboardInterfaceService.write('table', html);
- // FIXME:
+ // tell hooks to clean up
+ hooks.forEach((h) => h.onAfterCopy?.());
return true;
}
@@ -121,3 +141,103 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
return this._clipboardHooks.slice();
}
}
+
+/**
+ *
+ * @param matrix
+ * @param cols
+ * @param hooks
+ */
+export function getTableContent(matrix: number[][], cols: number[], hooks: ISheetClipboardHook[]) {}
+
+export function getSingleCellContent() {}
+
+/**
+ * Get content of a single td element.
+ * @param row index of the copied cell
+ * @param col index of the copied cell
+ * @returns
+ */
+function getTDContent(
+ row: number,
+ col: number,
+ hooks: ISheetClipboardHook[],
+ matrix: ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }>
+) {
+ const v = matrix.getValue(row, col);
+ const properties = hooks
+ .map((hook) => hook.onCopy?.(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) || '', '');
+ return `<td${str}>${content}</td>`;
+}
+
+/**
+ *
+ * @param row index of the copied row
+ * @param cols
+ * @param hooks
+ * @returns
+ */
+function getRowContent(
+ row: number,
+ cols: number[],
+ hooks: ISheetClipboardHook[],
+ matrix: ObjectMatrix<ICellData & { rowSpan?: number; colSpan?: number }>
+) {
+ const properties = hooks.map((hook) => hook.onCopyRow?.(row)).filter((v) => !!v) as IClipboardPropertyItem[];
+ const mergedProperties = mergeProperties(properties);
+ const str = zipClipboardPropertyItemToString(mergedProperties);
+ const tds = cols
+ .map((col) => getTDContent(row, col, hooks, matrix))
+ .filter((v) => !!v)
+ .join('');
+
+ return `<tr${str}>${tds}</tr>`;
+}
+
+function getColStyle(cols: number[], hooks: ISheetClipboardHook[]) {
+ const str = cols
+ .map((col) => {
+ const properties = hooks
+ .map((hook) => hook.onCopyColumn?.(col))
+ .filter((v) => !!v) as IClipboardPropertyItem[];
+ const mergedProperties = mergeProperties(properties);
+ const str = zipClipboardPropertyItemToString(mergedProperties);
+ return `<col ${str}>`;
+ })
+ .join('');
+
+ return `<colgroup>${str}</colgroup>`;
+}
+
+function mergeProperties(properties: IClipboardPropertyItem[]): IClipboardPropertyItem {
+ return properties.reduce((acc, cur) => {
+ const keys = Object.keys(cur);
+ keys.forEach((key) => {
+ if (!acc[key]) {
+ acc[key] = cur[key];
+ } else {
+ acc[key] += `;${cur[key]}`;
+ }
+ });
+ return acc;
+ }, {});
+}
+
+function zipClipboardPropertyItemToString(item: IClipboardPropertyItem) {
+ return Object.keys(item).reduce((acc, cur) => {
+ acc += ` ${cur}="${item[cur]}"`;
+ return acc;
+ }, '');
+}
+
+function getArrayFromTo(f: number, to: number): number[] {
+ const arr: number[] = [];
+ for (let i = f; i <= to; i++) {
+ arr.push(i);
+ }
+ return arr;
+}