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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(sheet): pasting plain text with newline and tab characters (#2678)
William Moorede987ccd27c6
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-notepad.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-notepad.spec.tsnew file mode 100644index 0000000000..7574609b52--- /dev/null+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-notepad.spec.ts@@ -0,0 +1,142 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICellData, Nullable, Univer } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from '@univerjs/core';+import {+ AddWorksheetMergeMutation,+ MoveRangeMutation,+ NORMAL_SELECTION_PLUGIN_NAME,+ RemoveWorksheetMergeMutation,+ SelectionManagerService,+ SetRangeValuesMutation,+ SetSelectionsOperation,+ SetWorksheetColWidthMutation,+ SetWorksheetRowHeightMutation,+} from '@univerjs/sheets';+import type { Injector } from '@wendellhu/redi';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { ISheetClipboardService } from '../clipboard.service';+import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';+import { clipboardTestBed } from './clipboard-test-bed';+import { plainTextByNotepad } from './constant';++describe('Test clipboard', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;+ let sheetClipboardService: ISheetClipboardService;+ let sheetSkeletonManagerService: SheetSkeletonManagerService;++ let getValues: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Array<Array<Nullable<ICellData>>> | undefined;++ beforeEach(async () => {+ const testBed = clipboardTestBed({+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ cellData: {+ 0: {+ 0: {+ v: 1,+ },+ },+ },+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: [],+ styles: {},+ });+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);+ commandService.registerCommand(SetRangeValuesMutation);+ commandService.registerCommand(SetWorksheetRowHeightMutation);+ commandService.registerCommand(SetWorksheetColWidthMutation);+ commandService.registerCommand(AddWorksheetMergeMutation);+ commandService.registerCommand(RemoveWorksheetMergeMutation);+ commandService.registerCommand(SetSelectionsOperation);+ commandService.registerCommand(MoveRangeMutation);++ sheetSkeletonManagerService = get(SheetSkeletonManagerService);+ sheetClipboardService = get(ISheetClipboardService);++ getValues = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Array<Array<Nullable<ICellData>>> | undefined =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValues();+ });++ afterEach(() => {+ univer?.dispose();+ });++ describe('Test paste from notepad ', () => {+ beforeEach(() => {+ const selectionManager = get(SelectionManagerService);++ selectionManager.setCurrentSelection({+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,+ unitId: 'test',+ sheetId: 'sheet1',+ });+ const startRow = 1;+ const startColumn = 1;+ const endRow = 1;+ const endColumn = 1;++ selectionManager.add([+ {+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);++ sheetSkeletonManagerService.setCurrent({+ sheetId: 'sheet1',+ });+ });+ it('test value with paste plain text', async () => {+ const worksheet = get(IUniverInstanceService).getUniverSheetInstance('test')?.getSheetBySheetId('sheet1');+ if (!worksheet) return false;+ const res = await sheetClipboardService.legacyPaste('', plainTextByNotepad);+ expect(res).toBeTruthy();+ expect(getValues(1, 1, 1, 1)?.[0]?.[0]?.v).toEqual('day');+ expect(getValues(2, 2, 2, 2)?.[0]?.[0]?.v).toEqual(2.1);+ expect(getValues(1, 2, 1, 2)?.[0]?.[0]?.v).toEqual('2024年五一假期:相较23年');+ expect(getValues(7, 3, 7, 3)?.[0]?.[0]?.v).toEqual(-31.3);+ });+ });+});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/constant.ts b/packages/sheets-ui/src/services/clipboard/__tests__/constant.tsindex 859b567cbb..33036c475c 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/constant.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/constant.ts@@ -35,3 +35,6 @@ export const rotateSampleByUniver = '<html><head></head><body><google data-copy-export const alignmentSampleByExcel = '<html xmlns:v="urn:schemas-microsoft-com:vml"\r\nxmlns:o="urn:schemas-microsoft-com:office:office"\r\nxmlns:x="urn:schemas-microsoft-com:office:excel"\r\nxmlns="http://www.w3.org/TR/REC-html40">\r\n\r\n<head>\r\n<meta http-equiv=Content-Type content="text/html; charset=utf-8">\r\n<meta name=ProgId content=Excel.Sheet>\r\n<meta name=Generator content="Microsoft Excel 15">\r\n<link id=Main-File rel=Main-File\r\nhref="file:////Users/yuanbin/Library/Group%20Containers/UBF8T346G9.Office/TemporaryItems/msohtmlclip/clip.htm">\r\n<link rel=File-List\r\nhref="file:////Users/yuanbin/Library/Group%20Containers/UBF8T346G9.Office/TemporaryItems/msohtmlclip/clip_filelist.xml">\r\n<style>\r\n\x3C!--table\r\n\t{mso-displayed-decimal-separator:"\\.";\r\n\tmso-displayed-thousand-separator:"\\,";}\r\n@page\r\n\t{margin:.75in .7in .75in .7in;\r\n\tmso-header-margin:.3in;\r\n\tmso-footer-margin:.3in;}\r\ntr\r\n\t{mso-height-source:auto;\r\n\tmso-ruby-visibility:none;}\r\ncol\r\n\t{mso-width-source:auto;\r\n\tmso-ruby-visibility:none;}\r\nbr\r\n\t{mso-data-placement:same-cell;}\r\ntd\r\n\t{padding-top:1px;\r\n\tpadding-right:1px;\r\n\tpadding-left:1px;\r\n\tmso-ignore:padding;\r\n\tcolor:black;\r\n\tfont-size:12.0pt;\r\n\tfont-weight:400;\r\n\tfont-style:normal;\r\n\ttext-decoration:none;\r\n\tfont-family:等线;\r\n\tmso-generic-font-family:auto;\r\n\tmso-font-charset:134;\r\n\tmso-number-format:General;\r\n\ttext-align:general;\r\n\tvertical-align:middle;\r\n\tborder:none;\r\n\tmso-background-source:auto;\r\n\tmso-pattern:auto;\r\n\tmso-protection:locked visible;\r\n\twhite-space:nowrap;\r\n\tmso-rotate:0;}\r\n.xl65\r\n\t{text-align:left;\r\n\tvertical-align:bottom;}\r\n.xl66\r\n\t{text-align:right;\r\n\tvertical-align:bottom;}\r\n.xl67\r\n\t{text-align:center;\r\n\tvertical-align:bottom;}\r\n.xl68\r\n\t{vertical-align:top;}\r\n.xl69\r\n\t{color:#44546A;\r\n\tfont-size:11.0pt;\r\n\tfont-weight:700;}\r\n.xl70\r\n\t{vertical-align:bottom;}\r\nruby\r\n\t{ruby-align:left;}\r\nrt\r\n\t{color:windowtext;\r\n\tfont-size:9.0pt;\r\n\tfont-weight:400;\r\n\tfont-style:normal;\r\n\ttext-decoration:none;\r\n\tfont-family:等线;\r\n\tmso-generic-font-family:auto;\r\n\tmso-font-charset:134;\r\n\tmso-char-type:none;\r\n\tdisplay:none;}\r\n-->\r\n</style>\r\n</head>\r\n\r\n<body link="#0563C1" vlink="#954F72">\r\n\r\n<table border=0 cellpadding=0 cellspacing=0 width=522 style=\'border-collapse:\r\n collapse;width:390pt\'>\r\n <col width=87 span=6 style=\'width:65pt\'>\r\n <tr height=88 style=\'mso-height-source:userset;height:66.0pt\'>\r\n\x3C!--StartFragment-->\r\n <td height=88 class=xl65 width=87 style=\'height:66.0pt;width:65pt\'>左对齐</td>\r\n <td class=xl66 width=87 style=\'width:65pt\'>右对齐</td>\r\n <td class=xl67 width=87 style=\'width:65pt\'>中间对齐</td>\r\n <td class=xl68 width=87 style=\'width:65pt\'>顶部</td>\r\n <td class=xl70 width=87 style=\'width:65pt\'>底部对齐</td>\r\n <td class=xl69 width=87 style=\'width:65pt\'>居中对齐</td>\r\n\x3C!--EndFragment-->\r\n </tr>\r\n</table>\r\n\r\n</body>\r\n\r\n</html>\r\n';export const alignmentSampleByGoogle = '<google-sheets-html-origin><style type="text/css">\x3C!--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" data-sheets-root="1"><colgroup><col width="100"/><col width="100"/><col width="100"/><col width="100"/><col width="100"/><col width="100"/></colgroup><tbody><tr style="height:65px;"><td style="overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;font-family:Arial;font-size:12pt;font-weight:normal;" data-sheets-value="{"1":2,"2":"左对齐"}">左对齐</td><td style="overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;font-family:Arial;font-size:12pt;font-weight:normal;text-align:right;" data-sheets-value="{"1":2,"2":"右对齐"}">右对齐</td><td style="overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;font-family:Arial;font-size:12pt;font-weight:normal;text-align:center;" data-sheets-value="{"1":2,"2":"中间对齐"}">中间对齐</td><td style="overflow:hidden;padding:2px 3px 2px 3px;vertical-align:top;font-family:Arial;font-size:12pt;font-weight:normal;" data-sheets-value="{"1":2,"2":"顶部"}">顶部</td><td style="overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;font-family:Arial;font-size:12pt;font-weight:normal;" data-sheets-value="{"1":2,"2":"底部对齐"}">底部对齐</td><td style="overflow:hidden;padding:2px 3px 2px 3px;vertical-align:middle;font-family:Arial;font-size:11pt;font-weight:bold;color:#44546a;" data-sheets-value="{"1":2,"2":"居中对齐"}">居中对齐</td></tr></tbody></table>';export const alignmentSampleByUniver = '<html><head></head><body><google data-copy-id="rJhHMI" -sheets-html-origin=""><table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none"><colgroup><col width="73"><col width="73"><col width="73"><col width="73"><col width="73"><col width="73"></colgroup>\n<tbody><tr style="height: 66px;"><td style="color: rgb(0, 0, 0); font-size: 12pt; text-align: left; vertical-align: bottom; font-family: 等线; ">左对齐</td><td style="color: rgb(0, 0, 0); font-size: 12pt; text-align: right; vertical-align: bottom; font-family: 等线; ">右对齐</td><td style="color: rgb(0, 0, 0); font-size: 12pt; text-align: center; vertical-align: bottom; font-family: 等线; ">中间对齐</td><td style="color: rgb(0, 0, 0); font-size: 12pt; vertical-align: top; font-family: 等线; ">顶部</td><td style="color: rgb(0, 0, 0); font-size: 12pt; vertical-align: bottom; font-family: 等线; ">底部对齐</td><td style="color: rgb(68, 84, 106); font-size: 11pt; vertical-align: middle; font-weight: bold; font-family: 等线; ">居中对齐</td></tr></tbody></table></google></body></html>';++// plain-text+export const plainTextByNotepad = 'day\t2024年五一假期:相较23年\t相较19年\r\n公路总计\t2.1\t24.4\r\n公路非营业\t1.4\t39.2\r\n铁路\t1.4\t23.3\r\n民航\t8.1\t11.1\r\n公路营业性\t6.5\t-25.1\r\n水运\t6\t-31.3\r\n';diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.tsindex 82bed2f3d4..34a34f0ac0 100644--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts@@ -60,7 +60,7 @@ import type {} from './type';import { COPY_TYPE } from './type';import { USMToHtmlService } from './usm-to-html/convertor';-import { clipboardItemIsFromExcel, discreteRangeContainsRange, mergeSetRangeValues, rangeIntersectWithDiscreteRange } from './utils';+import { clipboardItemIsFromExcel, convertTextToTable, discreteRangeContainsRange, mergeSetRangeValues, rangeIntersectWithDiscreteRange } from './utils';export const PREDEFINED_HOOK_NAME = {DEFAULT_COPY: 'default-copy',@@ -235,7 +235,12 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardif (html) {return this._pasteHTML(html, PREDEFINED_HOOK_NAME.DEFAULT_PASTE);} else if (text) {- return this._pastePlainText(text, PREDEFINED_HOOK_NAME.DEFAULT_PASTE);+ // Converts text with tabs and newlines into an HTML table+ if (/[\n\t]/.test(text)) {+ return this._pasteHTML(convertTextToTable(text), PREDEFINED_HOOK_NAME.DEFAULT_PASTE);+ } else {+ return this._pastePlainText(text, PREDEFINED_HOOK_NAME.DEFAULT_PASTE);+ }}return Promise.resolve(false);diff --git a/packages/sheets-ui/src/services/clipboard/utils.ts b/packages/sheets-ui/src/services/clipboard/utils.tsindex 11334a3224..064b50c4a4 100644--- a/packages/sheets-ui/src/services/clipboard/utils.ts+++ b/packages/sheets-ui/src/services/clipboard/utils.ts@@ -178,3 +178,22 @@ export function discreteRangeContainsRange(discrete: IDiscreteRange, range: IRan}return true;}++export function convertTextToTable(text: string): string {+ const rows = text.trim().split('\n');++ let html = '<table>';++ rows.forEach((row) => {+ const columns = row.split('\t');+ html += '<tr>';+ columns.forEach((column) => {+ html += `<td>${column}</td>`;+ });+ html += '</tr>';+ });++ html += '</table>';++ return html;+}