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): duplicate sheet name copy (#2544)
Dushusir50f8f4d8b4c3
diff --git a/examples/src/data/sheets/demo/default-workbook-data-demo.ts b/examples/src/data/sheets/demo/default-workbook-data-demo.tsindex d7d2b54ada..3f8d0c5e08 100644--- a/examples/src/data/sheets/demo/default-workbook-data-demo.ts+++ b/examples/src/data/sheets/demo/default-workbook-data-demo.ts@@ -21412,6 +21412,9 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {4: {s: '46',},+ 5: {+ s: '46',+ },6: {s: '46',v: 'Entourage',@@ -21419,6 +21422,12 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {7: {s: '47',},+ 8: {+ s: '47',+ },+ 9: {+ s: '47',+ },10: {v: 'Borrower write-off',s: '53',@@ -21433,6 +21442,27 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {v: ' To To To',s: '48',},+ 3: {+ s: '48',+ },+ 4: {+ s: '48',+ },+ 5: {+ s: '48',+ },+ 6: {+ s: '48',+ },+ 7: {+ s: '48',+ },+ 8: {+ s: '48',+ },+ 9: {+ s: '48',+ },},4: {1: {@@ -21443,10 +21473,28 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {v: '(Capital) 万 仟 佰 拾 元 角 分',s: '49',},+ 3: {+ s: '49',+ },+ 4: {+ s: '49',+ },+ 5: {+ s: '49',+ },+ 6: {+ s: '49',+ },7: {v: '(Lower) ¥',s: '48',},+ 8: {+ s: '48',+ },+ 9: {+ s: '48',+ },},5: {1: {@@ -21460,9 +21508,18 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {v: 'ETR',s: '50',},+ 4: {+ s: '50',+ },5: {s: '50',},+ 6: {+ s: '50',+ },+ 7: {+ s: '50',+ },8: {v: 'Days',s: '50',@@ -21479,6 +21536,27 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {2: {s: '48',},+ 3: {+ s: '48',+ },+ 4: {+ s: '48',+ },+ 5: {+ s: '48',+ },+ 6: {+ s: '48',+ },+ 7: {+ s: '48',+ },+ 8: {+ s: '48',+ },+ 9: {+ s: '48',+ },},7: {1: {@@ -21495,6 +21573,9 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {4: {s: '50',},+ 5: {+ s: '50',+ },6: {v: 'Financial Manager',s: '50',@@ -21502,6 +21583,9 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {7: {s: '50',},+ 8: {+ s: '50',+ },9: {v: 'Payee',s: '51',@@ -21522,6 +21606,9 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {4: {s: '50',},+ 5: {+ s: '50',+ },6: {v: 'Cashier',s: '50',@@ -21529,6 +21616,9 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {7: {s: '50',},+ 8: {+ s: '50',+ },9: {s: '51',},@@ -21538,6 +21628,30 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {v: 'Record: The loan is used exclusively for travel expenses, and the travel expenses will not be written off without a business trip application.',s: '45',},+ 2: {+ s: '45',+ },+ 3: {+ s: '45',+ },+ 4: {+ s: '45',+ },+ 5: {+ s: '45',+ },+ 6: {+ s: '45',+ },+ 7: {+ s: '45',+ },+ 8: {+ s: '45',+ },+ 9: {+ s: '45',+ },},},tabColor: 'blue',@@ -22051,6 +22165,9 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {},},20: {+ 1: {+ s: '37',+ },5: {v: 'Tax',s: '39',@@ -22060,6 +22177,9 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {},},21: {+ 1: {+ s: '37',+ },5: {v: 'Freight',s: '39',@@ -22069,6 +22189,18 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {},},22: {+ 1: {+ s: '37',+ },+ 2: {+ s: '37',+ },+ 3: {+ s: '37',+ },+ 4: {+ s: '37',+ },5: {v: 'Total ',s: '39',diff --git a/packages/sheets-ui/src/controllers/menu/sheet.menu.ts b/packages/sheets-ui/src/controllers/menu/sheet.menu.tsindex 3d113a4be3..4a1eef603b 100644--- a/packages/sheets-ui/src/controllers/menu/sheet.menu.ts+++ b/packages/sheets-ui/src/controllers/menu/sheet.menu.ts@@ -33,6 +33,7 @@ import {import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';import { MenuItemType } from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';+import type { Subscriber } from 'rxjs';import { combineLatest, combineLatestWith, map, Observable } from 'rxjs';import { RemoveSheetConfirmCommand } from '../../commands/commands/remove-sheet-confirm.command';@@ -53,16 +54,13 @@ export function DeleteSheetMenuItemFactory(accessor: IAccessor): IMenuButtonItemid === InsertSheetMutation.id ||id === SetWorksheetHideMutation.id) {- const worksheets = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getWorksheets();- // loop through all worksheets Map to see if there is more than one visible sheet- const visibleSheets = Array.from(worksheets.values()).filter(- (sheet) => sheet.getConfig().hidden === BooleanNumber.FALSE- );-- subscriber.next(visibleSheets.length === 1);+ disableFunction(univerInstanceService, subscriber);}});- subscriber.next(false);++ // When there is only one sheet initialized, it is also necessary to disable+ disableFunction(univerInstanceService, subscriber);+return disposable.dispose;});const permissionDisable$ = getWorkbookPermissionDisable$(accessor, [WorkbookEditablePermission, WorkbookDeleteSheetPermission]);@@ -135,16 +133,13 @@ export function HideSheetMenuItemFactory(accessor: IAccessor): IMenuButtonItem {id === InsertSheetMutation.id ||id === SetWorksheetHideMutation.id) {- const worksheets = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getWorksheets();- // loop through all worksheets Map to see if there is more than one visible sheet- const visibleSheets = Array.from(worksheets.values()).filter(- (sheet) => sheet.getConfig().hidden === BooleanNumber.FALSE- );-- subscriber.next(visibleSheets.length === 1);+ disableFunction(univerInstanceService, subscriber);}});- subscriber.next(false);++ // When there is only one sheet initialized, it is also necessary to disable+ disableFunction(univerInstanceService, subscriber);+return disposable.dispose;}).pipe(combineLatestWith(getWorkbookPermissionDisable$(accessor, [WorkbookEditablePermission, WorkbookHideSheetPermission])),@@ -211,6 +206,13 @@ export function ShowMenuItemFactory(accessor: IAccessor): IMenuButtonItem {positions: [SheetMenuPosition.SHEET_BAR],title: 'sheetConfig.unhide',disabled$: new Observable<boolean>((subscriber) => {+ function disableFunction() {+ const worksheets = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getWorksheets();+ // loop through all worksheets Map to see if there is more than one sheet+ const visibleSheets = Array.from(worksheets.values());++ subscriber.next(visibleSheets.length === 1);+ }const disposable = commandService.onCommandExecuted((c) => {const id = c.id;if (@@ -218,17 +220,24 @@ export function ShowMenuItemFactory(accessor: IAccessor): IMenuButtonItem {id === InsertSheetMutation.id ||id === SetWorksheetHideMutation.id) {- const worksheets = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getWorksheets();- // loop through all worksheets Map to see if there is more than one sheet- const visibleSheets = Array.from(worksheets.values());-- subscriber.next(visibleSheets.length === 1);+ disableFunction();}});- subscriber.next(false);++ disableFunction();+return disposable.dispose;}).pipe(combineLatestWith(getWorkbookPermissionDisable$(accessor, [WorkbookEditablePermission, WorkbookHideSheetPermission])),map(([defaultDisabled, permissionDisabled]) => defaultDisabled || permissionDisabled)),};}++function disableFunction(univerInstanceService: IUniverInstanceService, subscriber: Subscriber<boolean>) {+ const worksheets = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getWorksheets();+ // loop through all worksheets Map to see if there is more than one visible sheet+ const visibleSheets = Array.from(worksheets.values()).filter(+ (sheet) => sheet.getConfig().hidden === BooleanNumber.FALSE+ );+ subscriber.next(visibleSheets.length === 1);+}diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsxindex 8316e1a03a..cdbed3d4ba 100644--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx@@ -112,7 +112,7 @@ export function SheetBarTabs() {setupSubscribeScroll(),setupSubscribeScrollX(),setupSubscribeRenameId(),- setupSubscribeAddSheet(),+ // When adding a sheet, it no longer slides, which has been uniformly handled in setupSlideTabBarUpdate];return () => {@@ -314,11 +314,6 @@ export function SheetBarTabs() {setTabEditor();});- const setupSubscribeAddSheet = () =>- sheetBarService.addSheet$.subscribe(() => {- slideTabBarRef.current.slideTabBar?.getScrollbar().scrollRight();- });-const updateScrollButtonState = (state: IScrollState) => {const { leftEnd, rightEnd } = state;// box-shadow: inset 10px 0px 10px -10px rgba(0, 0, 0, 0.2), inset -10px 0px 10px -10px rgba(0, 0, 0, 0.2);@@ -337,6 +332,13 @@ export function SheetBarTabs() {};const buttonScroll = (slideTabBar: SlideTabBar) => {+ // If the active sheet needs to display the statistics column, it will trigger a resize, which will cover the activeTabItem. You need to slide a little distance to display the active tab.+ const scrollX = slideTabBar.calculateActiveTabItemScrollX();+ if (scrollX) {+ const scrollBar = slideTabBar.getScrollbar();+ scrollBar.scrollX(scrollBar.getScrollX() + scrollX);+ }+sheetBarService.setScroll({leftEnd: slideTabBar.isLeftEnd(),rightEnd: slideTabBar.isRightEnd(),@@ -392,7 +394,7 @@ export function SheetBarTabs() {)}onVisibleChange={onVisibleChange}>- <div className={styles.slideTabBarContainer} ref={slideTabBarContainerRef}>+ <div className={styles.slideTabBarContainer} ref={slideTabBarContainerRef} onDragStart={(e) => e.preventDefault()}><div className={styles.slideTabBar} style={{ boxShadow }}>{sheetList.map((item) => (<SheetBarItem {...item} key={item.sheetId} selected={activeKey === item.sheetId} />diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.tsindex f63365698f..2c7d00e931 100644--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts@@ -442,6 +442,7 @@ export class SlideTabBar {*/protected _rightMoveX: number = 0;+ // eslint-disable-next-line max-lines-per-functionconstructor(config: Partial<SlideTabBarConfig>) {if (config.slideTabBarContainer == null) {throw new Error('not found slide-tab-bar root element');@@ -463,12 +464,19 @@ export class SlideTabBar {let lastPageX = 0;let lastPageY = 0;let lastTime = 0;+ // eslint-disable-next-line max-lines-per-functionthis._downAction = (downEvent: MouseEvent) => {// Waiting for the rename of the previous TABif (this._activeTabItem?.isEditMode()) {return;}+ // Clear timer+ if (this._longPressTimer) {+ clearTimeout(this._longPressTimer);+ this._longPressTimer = null;+ }+const slideItemId = (downEvent.target as HTMLElement)?.closest(`.${config.slideTabBarItemClassName}`)?.getAttribute('data-id');@@ -529,9 +537,10 @@ export class SlideTabBar {// Set a timer to delay dragging for 300 millisecondsthis._longPressTimer = setTimeout(() => {+ if (!activeSlideItemElement || this._activeTabItem?.isEditMode()) return;+this._activeTabItem?.enableFixed();this._startAutoScroll();- if (!activeSlideItemElement) return;// Set the mouse cursor to dragactiveSlideItemElement.setPointerCapture((downEvent as PointerEvent).pointerId);activeSlideItemElement.style.cursor = 'move';@@ -540,6 +549,10 @@ export class SlideTabBar {};this._upAction = (upEvent: MouseEvent) => {+ if (this._activeTabItem?.isEditMode()) {+ return;+ }+// Clear timerif (this._longPressTimer) {clearTimeout(this._longPressTimer);@@ -637,6 +650,7 @@ export class SlideTabBar {this._initConfig();this.removeListener();this.addListener();+ this.scrollToItem(currentIndex);}primeval(): HTMLElement {@@ -726,6 +740,24 @@ export class SlideTabBar {});}+ scrollToItem(index?: number): void {+ index = index ?? this._config.currentIndex;+ // Check index validity+ if (index < 0 || index >= this._slideTabItems.length) {+ console.error('Index out of bounds');+ return;+ }++ const right = this.calculateTabItemScrollX(index);+ this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + right);++ // Trigger a scroll event+ this._config.onScroll({+ leftEnd: this.isLeftEnd(),+ rightEnd: this.isRightEnd(),+ });+ }+calculateLeftScrollX(shouldFlipPage?: boolean): number {let scrollX = 0;const padding = 4;@@ -770,6 +802,58 @@ export class SlideTabBar {return scrollX;}+ calculateTabItemScrollX(index: number): number {+ let scrollX = 0;+ const padding = 4;++ const containerRect = this._slideTabBar.getBoundingClientRect();+ const containerLeftPosition = containerRect.left;+ const containerRightPosition = containerRect.left + containerRect.width;++ const itemReact = this._slideTabItems[index].getSlideTabItem().getBoundingClientRect();+ const itemLeft = itemReact.left;+ const itemWidth = itemReact.width;++ // Left side or part of left side+ if (itemLeft - padding * 2 < containerLeftPosition) {+ scrollX = itemLeft - containerLeftPosition - padding;+ }++ // Right side or part of right side+ if (itemLeft + itemWidth + padding * 2 > containerRightPosition) {+ scrollX = itemLeft + itemWidth - containerRightPosition + padding;+ }++ return scrollX;+ }++ calculateActiveTabItemScrollX(): number {+ let scrollX = 0;+ const padding = 4;++ const containerRect = this._slideTabBar.getBoundingClientRect();+ const containerLeftPosition = containerRect.left;+ const containerRightPosition = containerRect.left + containerRect.width;++ const itemReact = this._activeTabItem?.getSlideTabItem().getBoundingClientRect();+ if (!itemReact) return 0;++ const itemLeft = itemReact.left;+ const itemWidth = itemReact.width;++ // Part of left side+ if (itemLeft - padding * 2 < containerLeftPosition && itemLeft + itemWidth > containerLeftPosition) {+ scrollX = itemLeft - containerLeftPosition - padding;+ }++ // Part of right side+ if (itemLeft < containerRightPosition && itemLeft + itemWidth + padding * 2 > containerRightPosition) {+ scrollX = itemLeft + itemWidth - containerRightPosition + padding;+ }++ return scrollX;+ }+destroy() {this._downActionX = 0;this._moveActionX = 0;diff --git a/packages/sheets/src/commands/commands/__tests__/copy-worksheet.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/copy-worksheet.command.spec.tsindex 7b990dff7b..efdbe80c96 100644--- a/packages/sheets/src/commands/commands/__tests__/copy-worksheet.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/copy-worksheet.command.spec.ts@@ -15,7 +15,7 @@*/import type { Univer, Workbook, Worksheet } from '@univerjs/core';-import { ICommandService, IUniverInstanceService, LocaleService, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, LocaleService, LocaleType, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';import type { Injector } from '@wendellhu/redi';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -24,7 +24,7 @@ import zhCN from '../../../locale/zh-CN';import { InsertSheetMutation } from '../../mutations/insert-sheet.mutation';import { RemoveSheetMutation } from '../../mutations/remove-sheet.mutation';import { SetWorksheetActiveOperation } from '../../operations/set-worksheet-active.operation';-import { CopySheetCommand } from '../copy-worksheet.command';+import { CopySheetCommand, getCopyUniqueSheetName } from '../copy-worksheet.command';import { RemoveSheetCommand } from '../remove-sheet.command';import { SetWorksheetActivateCommand } from '../set-worksheet-activate.command';import { createCommandTestBed } from './create-command-test-bed';@@ -89,6 +89,21 @@ describe('Test copy worksheet commands', () => {expect(getSheetCopyPart(newSheet2)).toEqual(getSheetCopyPart(oldSheet2));});++ it('Function getCopyUniqueSheetName', async () => {+ const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ if (!workbook) throw new Error('This is an error');++ const localeService = get(LocaleService);+ localeService.setLocale(LocaleType.EN_US);+ const name = 'Sheet1';++ expect(getCopyUniqueSheetName(workbook, localeService, name)).toBe('Sheet1(Copy)');++ workbook.addWorksheet('sheet1-copy', 0, { name: 'Sheet1(Copy)' });++ expect(getCopyUniqueSheetName(workbook, localeService, name)).toBe('Sheet1(Copy2)');+ });});});});diff --git a/packages/sheets/src/commands/commands/copy-worksheet.command.ts b/packages/sheets/src/commands/commands/copy-worksheet.command.tsindex b1cc4d3c63..7c863658e2 100644--- a/packages/sheets/src/commands/commands/copy-worksheet.command.ts+++ b/packages/sheets/src/commands/commands/copy-worksheet.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICommand } from '@univerjs/core';+import type { ICommand, Workbook } from '@univerjs/core';import {CommandType,ICommandService,@@ -54,7 +54,7 @@ export const CopySheetCommand: ICommand = {const { workbook, worksheet, unitId } = target;const config = Tools.deepClone(worksheet.getConfig());- config.name += localeService.t('sheets.tabs.sheetCopy');+ config.name = getCopyUniqueSheetName(workbook, localeService, config.name);config.id = Tools.generateRandomId();const sheetIndex = workbook.getSheetIndex(worksheet);@@ -81,3 +81,15 @@ export const CopySheetCommand: ICommand = {return false;},};++// If Sheet1(Copy) already exists and you copy Sheet1, you should get Sheet1(Copy2)+export function getCopyUniqueSheetName(workbook: Workbook, localeService: LocaleService, name: string): string {+ let output = name + localeService.t('sheets.tabs.sheetCopy', '');+ let count = 2;++ while (workbook.checkSheetName(output)) {+ output = name + localeService.t('sheets.tabs.sheetCopy', `${count}`);+ count++;+ }+ return output;+}diff --git a/packages/sheets/src/locale/en-US.ts b/packages/sheets/src/locale/en-US.tsindex 7eb06fb9da..6bf447ac35 100644--- a/packages/sheets/src/locale/en-US.ts+++ b/packages/sheets/src/locale/en-US.ts@@ -19,7 +19,7 @@ import type zhCN from './zh-CN';const locale: typeof zhCN = {sheets: {tabs: {- sheetCopy: '(Copy)',+ sheetCopy: '(Copy{0})',sheet: 'Sheet',},info: {diff --git a/packages/sheets/src/locale/ru-RU.ts b/packages/sheets/src/locale/ru-RU.tsindex 26a64a2e03..115ac6f45f 100644--- a/packages/sheets/src/locale/ru-RU.ts+++ b/packages/sheets/src/locale/ru-RU.ts@@ -19,7 +19,7 @@ import type zhCN from './zh-CN';const locale: typeof zhCN = {sheets: {tabs: {- sheetCopy: '(Копия)',+ sheetCopy: '(Копия{0})',sheet: 'Лист',},info: {diff --git a/packages/sheets/src/locale/zh-CN.ts b/packages/sheets/src/locale/zh-CN.tsindex 213c9176b2..61dcf170f6 100644--- a/packages/sheets/src/locale/zh-CN.ts+++ b/packages/sheets/src/locale/zh-CN.ts@@ -17,7 +17,7 @@const locale = {sheets: {tabs: {- sheetCopy: '(副本)',+ sheetCopy: '(副本{0})',sheet: '工作表',},info: {