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: support copy and paste across pages (#7160)

wpxp1234565f0b473caee5
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
index 2ad70cb936..8b0d9b0b00 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
@@ -437,6 +437,7 @@ describe('Test cut command with formulas', () => {
beforeEach(() => {
const testBed = clipboardTestBed(createFormulaClipboardWorkbookData(), [
[UpdateFormulaController],
+ [FormulaClipboardController],
]);
univer = testBed.univer;
@@ -452,6 +453,7 @@ describe('Test cut command with formulas', () => {
sheetClipboardService = get(ISheetClipboardService);
get(UpdateFormulaController);
+ get(FormulaClipboardController);
getValues = (
startRow: number,
@@ -471,6 +473,90 @@ describe('Test cut command with formulas', () => {
univer.dispose();
});
+ it('pastes cross-page formula payload with relative reference offsets', async () => {
+ get(SheetsSelectionsService).addSelections([
+ {
+ range: { startRow: 4, startColumn: 3, endRow: 4, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ const formulaItem = {
+ types: ['web application/x-univer-sheets-formula', 'text/html'],
+ getType: async (type: string) => {
+ if (type === 'web application/x-univer-sheets-formula') {
+ return new Blob([JSON.stringify({
+ rowCount: 1,
+ columnCount: 1,
+ origin: {
+ row: 1,
+ column: 1,
+ },
+ formulas: [
+ {
+ row: 0,
+ column: 0,
+ f: '=C2',
+ },
+ ],
+ })], { type });
+ }
+
+ return new Blob([
+ '<google-sheets-html-origin><table><tbody><tr><td>formula result</td></tr></tbody></table></google-sheets-html-origin>',
+ ], { type });
+ },
+ } as unknown as ClipboardItem;
+
+ await sheetClipboardService.paste(formulaItem);
+
+ expect(getValues(4, 3, 4, 3)?.[0][0]?.f).toBe('=E5');
+ });
+
+ it('keeps non-formula html cells when formula payload restores formulas', async () => {
+ get(SheetsSelectionsService).addSelections([
+ {
+ range: { startRow: 4, startColumn: 3, endRow: 4, endColumn: 4, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ const formulaItem = {
+ types: ['web application/x-univer-sheets-formula', 'text/html'],
+ getType: async (type: string) => {
+ if (type === 'web application/x-univer-sheets-formula') {
+ return new Blob([JSON.stringify({
+ rowCount: 1,
+ columnCount: 2,
+ origin: {
+ row: 1,
+ column: 1,
+ },
+ formulas: [
+ {
+ row: 0,
+ column: 1,
+ f: '=B2',
+ },
+ ],
+ })], { type });
+ }
+
+ return new Blob([
+ '<google-sheets-html-origin><table><tbody><tr><td>10</td><td>10</td></tr></tbody></table></google-sheets-html-origin>',
+ ], { type });
+ },
+ } as unknown as ClipboardItem;
+
+ await sheetClipboardService.paste(formulaItem);
+
+ const values = getValues(4, 3, 4, 4);
+ expect(values?.[0][0]?.v).toBe(10);
+ expect(values?.[0][1]?.f).toBe('=D5');
+ });
+
async function cutPaste(
fromRange: { rows: number[]; cols: number[] },
toRange: { startRow: number; startColumn: number; endRow: number; endColumn: number },
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 1bb167bcd8..6fbfebb2df 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -184,6 +184,7 @@ export {
export type { IDropdownParam } from './services/cell-dropdown-manager.service';
export { CellPopupManagerService } from './services/cell-popup-manager.service';
export {
+ FORMULA_CLIPBOARD_MIME_TYPE,
getMatrixPlainText,
ISheetClipboardService,
PREDEFINED_HOOK_NAME,
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
index 17e4d91f40..1129ddf7de 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
@@ -36,7 +36,7 @@ import {
Workbook,
} from '@univerjs/core';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
+import { SetSelectionsOperation, SetWorksheetActiveOperation, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
import {
IClipboardInterfaceService,
INotificationService,
@@ -61,7 +61,7 @@ class NoopNotificationService {
}
class TestClipboardInterfaceService {
- readonly writes: Array<{ text: string; html: string }> = [];
+ readonly writes: Array<{ text: string; html: string; customData?: Record<string, string> }> = [];
get supportClipboard(): boolean {
return true;
@@ -71,8 +71,8 @@ class TestClipboardInterfaceService {
this.writes.push({ text, html: '' });
}
- async write(text: string, html: string): Promise<void> {
- this.writes.push({ text, html });
+ async write(text: string, html: string, customData?: Record<string, string>): Promise<void> {
+ this.writes.push({ text, html, customData });
}
async readText(): Promise<string> {
@@ -86,6 +86,7 @@ class TestClipboardInterfaceService {
interface ITestCell {
v?: string;
+ f?: string;
s?: unknown;
rowSpan?: number;
colSpan?: number;
@@ -157,6 +158,9 @@ function createTestContext() {
injector.add([LocaleService]);
injector.add([ErrorService]);
injector.add([ISheetClipboardService, { useClass: SheetClipboardService }]);
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(SetSelectionsOperation);
+ commandService.registerCommand(SetWorksheetActiveOperation);
const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;
const workbook = injector.createInstance(Workbook, {
id: 'unit-1',
@@ -267,6 +271,59 @@ describe('SheetClipboardService', () => {
expect(copyId && service.copyContentCache().get(copyId)?.copyType).toBe(COPY_TYPE.COPY);
});
+ it('writes formula clipboard payload for copyable formula cells', async () => {
+ const { injector, service } = createTestContext();
+ selectRange(injector, 1, 2, 2, 3);
+
+ service.addClipboardHook({
+ id: PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY,
+ onCopyCellContent(row: number, column: number) {
+ return row === 2 && column === 3 ? '=A1+B1' : '';
+ },
+ } as never);
+
+ expect(await service.copy()).toBe(true);
+
+ const clipboard = injector.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;
+ const formulaPayload = clipboard.writes[0].customData?.['web application/x-univer-sheets-formula'];
+
+ expect(formulaPayload).toBe(JSON.stringify({
+ rowCount: 2,
+ columnCount: 2,
+ origin: {
+ row: 1,
+ column: 2,
+ },
+ formulas: [
+ {
+ row: 1,
+ column: 1,
+ f: '=A1+B1',
+ },
+ ],
+ }));
+ });
+
+ it('does not write formula clipboard payload when filtered rows are skipped', async () => {
+ const { injector, service } = createTestContext();
+ selectRange(injector, 1, 2, 2, 3);
+
+ service.addClipboardHook({
+ id: PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY,
+ getFilteredOutRows() {
+ return [1];
+ },
+ onCopyCellContent(row: number, column: number) {
+ return row === 2 && column === 3 ? '=A1+B1' : '';
+ },
+ } as never);
+
+ expect(await service.copy()).toBe(true);
+
+ const clipboard = injector.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;
+ expect(clipboard.writes[0].customData?.['web application/x-univer-sheets-formula']).toBeUndefined();
+ });
+
it('records cut selections as cut copy cache entries', async () => {
const { injector, service } = createTestContext();
selectCell(injector);
@@ -306,6 +363,73 @@ describe('SheetClipboardService', () => {
expect(pastedFiles).toEqual([{ name: 'clipboard-image.png', pasteType: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT }]);
});
+ it('routes formula clipboard payload to structured paste before html fallback', async () => {
+ const { injector, service } = createTestContext();
+ selectCell(injector, 5, 6);
+ const pasted: Array<{ pasteFrom: ITestDiscreteRange | undefined; formula: string | undefined }> = [];
+
+ service.addClipboardHook({
+ id: 'formula-payload-paste',
+ onPasteCells(pasteFrom: { range: ITestDiscreteRange } | null, _pasteTo: unknown, data: ObjectMatrix<ITestCell>) {
+ pasted.push({
+ pasteFrom: pasteFrom?.range,
+ formula: data.getValue(0, 0)?.f,
+ });
+ return { redos: [], undos: [] };
+ },
+ } as never);
+
+ const formulaItem = new MockClipboardItem({
+ 'web application/x-univer-sheets-formula': JSON.stringify({
+ rowCount: 1,
+ columnCount: 1,
+ origin: {
+ row: 1,
+ column: 2,
+ },
+ formulas: [
+ {
+ row: 0,
+ column: 0,
+ f: '=A1+B1',
+ },
+ ],
+ }),
+ 'text/html': '<table><tbody><tr><td>html fallback</td></tr></tbody></table>',
+ });
+
+ expect(await service.paste(formulaItem as unknown as ClipboardItem)).toBe(true);
+ expect(pasted).toEqual([{
+ pasteFrom: {
+ rows: [1],
+ cols: [2],
+ },
+ formula: '=A1+B1',
+ }]);
+ });
+
+ it('falls back to html paste when formula clipboard payload is invalid', async () => {
+ const { injector, service } = createTestContext();
+ selectCell(injector);
+ const pastedHtml: string[] = [];
+
+ service.addClipboardHook({
+ id: 'html-fallback-paste',
+ onPasteCells() {
+ pastedHtml.push('html');
+ return { redos: [], undos: [] };
+ },
+ } as never);
+
+ const formulaItem = new MockClipboardItem({
+ 'web application/x-univer-sheets-formula': '{invalid',
+ 'text/html': '<table><tbody><tr><td>html fallback</td></tr></tbody></table>',
+ });
+
+ expect(await service.paste(formulaItem as unknown as ClipboardItem)).toBe(true);
+ expect(pastedHtml).toEqual(['html']);
+ });
+
it('returns false when a clipboard item has no usable sheet content', async () => {
const service = createService();
const emptyItem = new MockClipboardItem({});
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/mock-clipboard.ts b/packages/sheets-ui/src/services/clipboard/__tests__/mock-clipboard.ts
index 271e2f564a..c80ff390c8 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/mock-clipboard.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/mock-clipboard.ts
@@ -48,6 +48,7 @@ interface IMockClipboardProps {
'text/plain'?: string;
'text/html'?: string;
'image/png'?: string;
+ [key: string]: string | undefined;
}
export class MockClipboard {
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index a41c484e65..2a9194b316 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -58,6 +58,7 @@ import {
ILogService,
Inject,
Injector,
+ isFormulaString,
isNotNullOrUndefined,
IUndoRedoService,
IUniverInstanceService,
@@ -139,12 +140,29 @@ const IMAGE_MIME_TO_EXTENSION = {
[FILE__BMP_CLIPBOARD_MIME_TYPE]: 'bmp',
} as const;
+export const FORMULA_CLIPBOARD_MIME_TYPE = 'web application/x-univer-sheets-formula';
+
+interface IFormulaClipboardPayload {
+ rowCount: number;
+ columnCount: number;
+ origin: {
+ row: number;
+ column: number;
+ };
+ formulas: Array<{
+ row: number;
+ column: number;
+ f: string;
+ }>;
+}
+
interface ICopyContent {
copyId: string;
plain: string;
html: string;
matrixFragment: ObjectMatrix<ICellDataWithSpanAndDisplay>;
discreteRange: IDiscreteRange;
+ formulaClipboardPayload?: string;
}
/**
@@ -263,6 +281,15 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
hooks.forEach((h) => h.onBeforeCopy?.(workbookId, worksheetId, range, copyType));
const copyContent = this._generateCopyContent(workbookId, worksheetId, range, hooks, copyHookType);
+ if (copyContent && copyType === COPY_TYPE.COPY) {
+ copyContent.formulaClipboardPayload = this._generateFormulaClipboardPayload(
+ workbookId,
+ worksheetId,
+ range,
+ copyContent,
+ hooks
+ );
+ }
hooks.forEach((h) => h.onAfterCopy?.());
return copyContent;
}
@@ -290,7 +317,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
// 2. extract copy content for both internal and external
- const { html, plain, matrixFragment, copyId, discreteRange } = copyContent;
+ const { html, plain, matrixFragment, copyId, discreteRange, formulaClipboardPayload } = copyContent;
// 3. cache the copy content for internal paste
this._copyContentCache.set(copyId, {
@@ -302,7 +329,11 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
});
// 4. write html and get plain text info the clipboard interface
- await this._clipboardInterfaceService.write(plain, html);
+ await this._clipboardInterfaceService.write(
+ plain,
+ html,
+ formulaClipboardPayload ? { [FORMULA_CLIPBOARD_MIME_TYPE]: formulaClipboardPayload } : undefined
+ );
// 5. mark the copy range
this._markSelectionService.removeAllShapes();
@@ -329,6 +360,10 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
types.indexOf(HTML_CLIPBOARD_MIME_TYPE) !== -1
? await item.getType(HTML_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text())
: '';
+ const formulaClipboardPayload =
+ types.indexOf(FORMULA_CLIPBOARD_MIME_TYPE) !== -1
+ ? await item.getType(FORMULA_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text()).catch(() => '')
+ : '';
const imageIndex = types.findIndex((type) => imageMimeTypeSet.has(type));
@@ -345,7 +380,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// After the pop-up window prompts, can paste the contents of the clipboard as much as possible.
}
- return this._pasteHTML(html, pasteType);
+ return this._pasteHTML(html, pasteType, formulaClipboardPayload);
}
// clipboard item from excel may contain image, so we need to check if the clipboard item is from excel
@@ -537,6 +572,60 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
};
}
+ private _generateFormulaClipboardPayload(
+ unitId: string,
+ subUnitId: string,
+ range: IRange,
+ copyContent: ICopyContent,
+ hooks: ISheetClipboardHook[]
+ ): string | undefined {
+ if (this._hasFilteredRows(unitId, subUnitId, range, hooks)) {
+ return undefined;
+ }
+
+ const { startRow, startColumn, endRow, endColumn } = range;
+ const rowCount = endRow - startRow + 1;
+ const columnCount = endColumn - startColumn + 1;
+ const formulaOnlyHook = hooks.find((hook) => hook.id === PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY);
+ const formulas: IFormulaClipboardPayload['formulas'] = [];
+
+ for (let row = 0; row < rowCount; row++) {
+ for (let column = 0; column < columnCount; column++) {
+ const formula = formulaOnlyHook?.onCopyCellContent?.(startRow + row, startColumn + column) ||
+ copyContent.matrixFragment.getValue(row, column)?.f;
+
+ if (typeof formula === 'string' && isFormulaString(formula)) {
+ formulas.push({
+ row,
+ column,
+ f: formula,
+ });
+ }
+ }
+ }
+
+ if (!formulas.length) {
+ return undefined;
+ }
+
+ return JSON.stringify({
+ rowCount,
+ columnCount,
+ origin: {
+ row: startRow,
+ column: startColumn,
+ },
+ formulas,
+ } satisfies IFormulaClipboardPayload);
+ }
+
+ private _hasFilteredRows(unitId: string, subUnitId: string, range: IRange, hooks: ISheetClipboardHook[]): boolean {
+ return hooks.some((hook) => {
+ const rows = hook.getFilteredOutRows?.(unitId, subUnitId, range);
+ return !!rows?.length;
+ });
+ }
+
private _notifyClipboardHook() {
this._clipboardHooks$.next(this._clipboardHooks);
}
@@ -615,15 +704,15 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
});
}
- private async _pasteHTML(html: string, pasteType: IPasteHookValueType): Promise<boolean> {
+ private async _pasteHTML(html: string, pasteType: IPasteHookValueType, formulaClipboardPayload?: string): Promise<boolean> {
const copyId = extractId(html);
if (copyId && this._copyContentCache.get(copyId)) {
return this._pasteInternal(copyId, pasteType);
}
- return this._pasteExternal(html, pasteType);
+ return this._pasteExternal(html, pasteType, formulaClipboardPayload);
}
- private async _pasteExternal(html: string, pasteType: IPasteHookValueType): Promise<boolean> {
+ private async _pasteExternal(html: string, pasteType: IPasteHookValueType, formulaClipboardPayload?: string): Promise<boolean> {
// this._logService.log('[SheetClipboardService]', 'pasting external content', html);
// steps of pasting:
@@ -635,6 +724,70 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
return false;
}
+ const sourceRange = formulaClipboardPayload
+ ? this._applyFormulaClipboardPayload(cellMatrix, formulaClipboardPayload)
+ : undefined;
+
+ return this._pasteExternalData({ rowProperties, colProperties, cellMatrix }, pasteType, sourceRange);
+ }
+
+ private _applyFormulaClipboardPayload(
+ cellMatrix: ObjectMatrix<ICellDataWithSpanInfo>,
+ text: string
+ ): IDiscreteRange | undefined {
+ let payload: IFormulaClipboardPayload;
+ try {
+ payload = JSON.parse(text) as IFormulaClipboardPayload;
+ } catch {
+ return undefined;
+ }
+
+ if (
+ !payload ||
+ !payload.origin ||
+ !Array.isArray(payload.formulas) ||
+ payload.rowCount <= 0 ||
+ payload.columnCount <= 0
+ ) {
+ return undefined;
+ }
+
+ cellMatrix.setValue(payload.rowCount - 1, payload.columnCount - 1, {
+ ...getEmptyCell(),
+ ...cellMatrix.getValue(payload.rowCount - 1, payload.columnCount - 1),
+ });
+ payload.formulas.forEach((formula) => {
+ if (
+ isFormulaString(formula.f) &&
+ formula.row >= 0 &&
+ formula.row < payload.rowCount &&
+ formula.column >= 0 &&
+ formula.column < payload.columnCount
+ ) {
+ cellMatrix.setValue(formula.row, formula.column, {
+ ...getEmptyCell(),
+ ...cellMatrix.getValue(formula.row, formula.column),
+ f: formula.f,
+ });
+ }
+ });
+
+ return {
+ rows: Array.from({ length: payload.rowCount }, (_, index) => payload.origin.row + index),
+ cols: Array.from({ length: payload.columnCount }, (_, index) => payload.origin.column + index),
+ };
+ }
+
+ private _pasteExternalData(
+ data: IUniverSheetCopyDataModel,
+ pasteType: IPasteHookValueType,
+ sourceRange?: IDiscreteRange
+ ): boolean {
+ const { rowProperties, colProperties, cellMatrix } = data;
+ 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
@@ -673,16 +826,26 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
// 4. execute these mutations by the one method
- const res = this._pasteUSM(
+ const source = sourceRange
+ ? {
+ range: sourceRange,
+ unitId: pasteTarget.unitId,
+ subUnitId: pasteTarget.subUnitId,
+ copyType: COPY_TYPE.COPY,
+ copyId: '',
+ }
+ : undefined;
+
+ return this._pasteUSM(
{
rowProperties,
colProperties,
cellMatrix,
},
pasteTarget,
- pasteType
+ pasteType,
+ source
);
- return res;
}
// eslint-disable-next-line max-lines-per-function