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(table): table name should not include space (#5601)
VicKunef875378f361
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 65c7af1c0f..96698c9359 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -141,7 +141,7 @@ export * from './shared';export { ImageCacheMap } from './shared/cache/image-cache';export { isBlackColor, isWhiteColor } from './shared/color/color-kit';export { cellToRange } from './shared/common';-export { nameCharacterCheck } from './shared/name';+export { customNameCharacterCheck, nameCharacterCheck } from './shared/name';export { type BBox, type IRTreeItem, RBush, RTree } from './shared/r-tree';export { getIntersectRange } from './shared/range';export { afterTime, bufferDebounceTime, convertObservableToBehaviorSubject, fromCallback, takeAfter } from './shared/rxjs';diff --git a/packages/core/src/shared/name.ts b/packages/core/src/shared/name.tsindex c933bba904..f79d583ffc 100644--- a/packages/core/src/shared/name.ts+++ b/packages/core/src/shared/name.ts@@ -22,7 +22,7 @@The name does not contain any of the following characters: : \ / ? * [ or ].The name is not empty.* @param name- * @returns+ * @returns {boolean} Returns true if the name is valid, false otherwise.*/export function nameCharacterCheck(name: string) {// Excel sheet name cannot be empty@@ -48,3 +48,38 @@ export function nameCharacterCheck(name: string) {return true;}++/**+ * Checks if the custom table name or custom name is valid based on the following criteria:+ * - The name cannot conflict with existing sheet names.+ * - The name cannot be empty.+ * - The name must start with a letter or underscore.+ * The name cannot contain spaces or invalid characters (e.g., :, \, /, ?, *, [, ]).+ * @param name The name need to check+ * @param sheetNameSet The set of existing sheet names to check against+ * @returns {boolean} Returns true if the name is valid, false otherwise.+ */+export function customNameCharacterCheck(name: string, sheetNameSet: Set<string>): boolean {+ // Custom table name cannot conflict with existing sheet names+ if (sheetNameSet.has(name)) {+ return false;+ }++ // Custom table name cannot be empty+ if (name.length === 0) {+ return false;+ }++ // Custom table name must start with a letter or underscore+ const validStart = /^[A-Za-z_]/;+ if (!validStart.test(name)) {+ return false;+ }+ // Custom table name cannot contain spaces or invalid characters+ const invalidChars = /[ :\\\/\?\*\[\]]/;+ if (invalidChars.test(name)) {+ return false;+ }++ return true;+}diff --git a/packages/core/src/sheets/__tests__/cust-name.spec.ts b/packages/core/src/sheets/__tests__/cust-name.spec.tsnew file mode 100644index 0000000000..e0cfb37b8a--- /dev/null+++ b/packages/core/src/sheets/__tests__/cust-name.spec.ts@@ -0,0 +1,68 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { describe, expect, it } from 'vitest';++import { customNameCharacterCheck } from '../../shared/name';++describe('customNameCharacterCheck', () => {+ it('should return false for empty name', () => {+ const result = customNameCharacterCheck('', new Set());+ expect(result).toBe(false);+ });++ it('should return false for name starting with invalid character', () => {+ const result = customNameCharacterCheck('1InvalidName', new Set());+ expect(result).toBe(false);+ });++ it('should return false for name containing invalid characters', () => {+ const result = customNameCharacterCheck('Invalid:Name', new Set());+ expect(result).toBe(false);+ });++ it('should return false for name conflicting with existing sheet names', () => {+ const sheetNameSet = new Set(['ExistingName']);+ const result = customNameCharacterCheck('ExistingName', sheetNameSet);+ expect(result).toBe(false);+ });++ it('should return true for valid name', () => {+ const result = customNameCharacterCheck('Valid_Name', new Set());+ expect(result).toBe(true);+ });++ it('should return true for valid name not conflicting with existing sheet names', () => {+ const sheetNameSet = new Set(['ExistingName']);+ const result = customNameCharacterCheck('NewName', sheetNameSet);+ expect(result).toBe(true);+ });++ it('should return false for name containing spaces', () => {+ const result = customNameCharacterCheck('Invalid Name', new Set());+ expect(result).toBe(false);+ });++ it('should return false for name containing special characters', () => {+ const result = customNameCharacterCheck('Invalid*Name', new Set());+ expect(result).toBe(false);+ });++ it('should return true for name starting with underscore', () => {+ const result = customNameCharacterCheck('_ValidName', new Set());+ expect(result).toBe(true);+ });+});diff --git a/packages/sheets-table-ui/src/locale/ca-ES.ts b/packages/sheets-table-ui/src/locale/ca-ES.tsindex 8f21717a95..64e424bbf7 100644--- a/packages/sheets-table-ui/src/locale/ca-ES.ts+++ b/packages/sheets-table-ui/src/locale/ca-ES.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: 'Segona línia',columnPrefix: 'Columna',tablePrefix: 'Taula',+ tableNameError: 'El nom de la taula no pot contenir espais, no pot començar amb un número i no pot ser idèntic a un nom de taula existent',insert: {main: 'Insereix una taula',diff --git a/packages/sheets-table-ui/src/locale/en-US.ts b/packages/sheets-table-ui/src/locale/en-US.tsindex 93d878ccf0..608859ab5f 100644--- a/packages/sheets-table-ui/src/locale/en-US.ts+++ b/packages/sheets-table-ui/src/locale/en-US.ts@@ -38,6 +38,7 @@ const locale = {secondLine: 'Second Line',columnPrefix: 'Column',tablePrefix: 'Table',+ tableNameError: 'Table name cannot contain spaces, cannot start with a number, and cannot be identical to an existing table name',insert: {main: 'Insert Table',diff --git a/packages/sheets-table-ui/src/locale/es-ES.ts b/packages/sheets-table-ui/src/locale/es-ES.tsindex 45931e1ca1..f157e20720 100644--- a/packages/sheets-table-ui/src/locale/es-ES.ts+++ b/packages/sheets-table-ui/src/locale/es-ES.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: 'Segunda línea',columnPrefix: 'Columna',tablePrefix: 'Tabla',+ tableNameError: 'El nombre de la tabla no puede contener espacios, no puede comenzar con un número y no puede ser idéntico a un nombre de tabla existente',insert: {main: 'Insertar tabla',diff --git a/packages/sheets-table-ui/src/locale/fa-IR.ts b/packages/sheets-table-ui/src/locale/fa-IR.tsindex d275b157a7..6cc03cd4c3 100644--- a/packages/sheets-table-ui/src/locale/fa-IR.ts+++ b/packages/sheets-table-ui/src/locale/fa-IR.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: 'خط دوم',columnPrefix: 'ستون',tablePrefix: 'جدول',+ tableNameError: 'لا يمكن أن يحتوي اسم الجدول على مسافات، ولا يمكن أن يبدأ برقم، ولا يمكن أن يتكرر مع أسماء الجداول الموجودة',insert: {main: 'درج جدول',diff --git a/packages/sheets-table-ui/src/locale/fr-FR.ts b/packages/sheets-table-ui/src/locale/fr-FR.tsindex 38ff7835fd..56154c5da4 100644--- a/packages/sheets-table-ui/src/locale/fr-FR.ts+++ b/packages/sheets-table-ui/src/locale/fr-FR.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: 'Deuxième ligne',columnPrefix: 'Colonne',tablePrefix: 'Tableau',+ tableNameError: 'Le nom du tableau ne peut pas contenir d\'espaces, ne peut pas commencer par un chiffre et ne peut pas être identique à un nom de tableau existant',insert: {main: 'Insérer un tableau',diff --git a/packages/sheets-table-ui/src/locale/ko-KR.ts b/packages/sheets-table-ui/src/locale/ko-KR.tsindex fc467710ca..bd16ad0f8c 100644--- a/packages/sheets-table-ui/src/locale/ko-KR.ts+++ b/packages/sheets-table-ui/src/locale/ko-KR.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: '두 번째 줄',columnPrefix: '열',tablePrefix: '표',+ tableNameError: '표 이름은 공백을 포함할 수 없으며 숫자로 시작할 수 없고 기존 표 이름과 중복될 수 없습니다',insert: {main: '표 삽입',diff --git a/packages/sheets-table-ui/src/locale/ru-RU.ts b/packages/sheets-table-ui/src/locale/ru-RU.tsindex 8be122fe54..43fac5a98b 100644--- a/packages/sheets-table-ui/src/locale/ru-RU.ts+++ b/packages/sheets-table-ui/src/locale/ru-RU.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: 'Вторая строка',columnPrefix: 'Столбец',tablePrefix: 'Таблица',+ tableNameError: 'Имя таблицы не может содержать пробелы, не может начинаться с цифры и не может совпадать с именем существующей таблицы',insert: {main: 'Вставить таблицу',diff --git a/packages/sheets-table-ui/src/locale/vi-VN.ts b/packages/sheets-table-ui/src/locale/vi-VN.tsindex bc142fecf4..4ea4f52ecd 100644--- a/packages/sheets-table-ui/src/locale/vi-VN.ts+++ b/packages/sheets-table-ui/src/locale/vi-VN.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: 'Dòng thứ hai',columnPrefix: 'Cột',tablePrefix: 'Bảng',+ tableNameError: 'Tên bảng không thể chứa khoảng trắng, không được bắt đầu bằng số và không được trùng với tên bảng đã có',insert: {main: 'Chèn bảng',diff --git a/packages/sheets-table-ui/src/locale/zh-CN.ts b/packages/sheets-table-ui/src/locale/zh-CN.tsindex 6a71beb4ad..514d7325c8 100644--- a/packages/sheets-table-ui/src/locale/zh-CN.ts+++ b/packages/sheets-table-ui/src/locale/zh-CN.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: '第二行',columnPrefix: '列',tablePrefix: '表格',+ tableNameError: '表格名称不能包含空格, 不能以数字开头,不能和已有表格名称重复',insert: {main: '表格插入',diff --git a/packages/sheets-table-ui/src/locale/zh-TW.ts b/packages/sheets-table-ui/src/locale/zh-TW.tsindex e6acb982f5..9a9125b4a1 100644--- a/packages/sheets-table-ui/src/locale/zh-TW.ts+++ b/packages/sheets-table-ui/src/locale/zh-TW.ts@@ -40,6 +40,7 @@ const locale: typeof enUS = {secondLine: '第二行',columnPrefix: '列',tablePrefix: '表格',+ tableNameError: '表格名稱不能包含空格, 不能以數字開頭,不能和已有表格名稱重複',insert: {main: '表格插入',diff --git a/packages/sheets-table/src/commands/commands/add-sheet-table.command.ts b/packages/sheets-table/src/commands/commands/add-sheet-table.command.tsindex 25a8f7c5c4..aaa7668867 100644--- a/packages/sheets-table/src/commands/commands/add-sheet-table.command.ts+++ b/packages/sheets-table/src/commands/commands/add-sheet-table.command.ts@@ -45,7 +45,7 @@ export const AddSheetTableCommand: ICommand<IAddSheetTableCommandParams> = {if (!tableName) {const tableManager = accessor.get(TableManager);const tableCount = tableManager.getTableList(params.unitId).length;- tableName = `${localeService.t('sheets-table.tablePrefix')} ${tableCount + 1}`;+ tableName = `${localeService.t('sheets-table.tablePrefix')}${tableCount + 1}`;}const redos: IMutationInfo[] = [];diff --git a/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts b/packages/sheets-table/src/commands/commands/set-sheet-table.command.tsindex 15086f1ba5..dcb765392b 100644--- a/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts+++ b/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import type { ICommand } from '@univerjs/core';+import type { ICommand, Workbook } from '@univerjs/core';import type { ITableSetConfig } from '../../types/type';import type { ISetSheetTableMutationParams } from '../mutations/set-sheet-table.mutation';-import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';+import { CommandType, customNameCharacterCheck, ICommandService, ILogService, IUndoRedoService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';import { TableManager } from '../../model/table-manager';import { IRangeOperationTypeEnum } from '../../types/type';import { SetSheetTableMutation } from '../mutations/set-sheet-table.mutation';@@ -30,6 +30,7 @@ export interface ISetSheetTableCommandParams extends ITableSetConfig {export const SetSheetTableCommand: ICommand<ISetSheetTableCommandParams> = {id: 'sheet.command.set-table-config',type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-functionhandler: (accessor, params) => {if (!params) {return false;@@ -45,7 +46,25 @@ export const SetSheetTableCommand: ICommand<ISetSheetTableCommandParams> = {const oldTableConfig: ITableSetConfig = {};const newTableConfig: ITableSetConfig = {};+ const localeService = accessor.get(LocaleService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);++ const sheetNameSet = new Set<string>();+ if (workbook) {+ workbook.getSheets().forEach((sheet) => {+ sheetNameSet.add(sheet.getName());+ });+ }+if (name) {+ const isValidName = customNameCharacterCheck(name, sheetNameSet);+ if (!isValidName) {+ const logService = accessor.get(ILogService);+ logService.warn(localeService.t('sheets-table.tableNameError'));+ return false;+ }+oldTableConfig.name = table.getDisplayName();newTableConfig.name = name;}diff --git a/packages/sheets-table/src/facade/f-workbook.ts b/packages/sheets-table/src/facade/f-workbook.tsindex 5bd67f5308..c8f8b6578c 100644--- a/packages/sheets-table/src/facade/f-workbook.ts+++ b/packages/sheets-table/src/facade/f-workbook.ts@@ -14,7 +14,9 @@* limitations under the License.*/+import type { Workbook } from '@univerjs/core';import type { IAddSheetTableCommandParams, IDeleteSheetTableParams, ISetSheetTableParams, ITableFilterItem, ITableInfo, ITableInfoWithUnitId, ITableOptions, ITableRange } from '@univerjs/sheets-table';+import { customNameCharacterCheck, ILogService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';import { AddSheetTableCommand, DeleteSheetTableCommand, SetSheetTableFilterCommand, SheetTableService } from '@univerjs/sheets-table';import { FWorkbook } from '@univerjs/sheets/facade';@@ -197,6 +199,22 @@ export class FWorkbookSheetsTableMixin extends FWorkbook implements IFWorkbookShoverride async addTable(subUnitId: string, tableName: string, rangeInfo: ITableRange, tableId?: string, options?: ITableOptions): Promise<string | undefined> {const sheetTableService = this._injector.get(SheetTableService);+ const localeService = this._injector.get(LocaleService);++ const univerInstanceService = this._injector.get(IUniverInstanceService);+ const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const sheetNameSet = new Set<string>();+ if (workbook) {+ workbook.getSheets().forEach((sheet) => {+ sheetNameSet.add(sheet.getName());+ });+ }+ const isValidName = customNameCharacterCheck(tableName, sheetNameSet);+ if (!isValidName) {+ const logService = this._injector.get(ILogService);+ logService.warn(localeService.t('sheets-table.tableNameError'));+ return undefined;+ }const addTableParams: IAddSheetTableCommandParams = {unitId: this.getId(),diff --git a/packages/sheets-table/src/facade/f-worksheet.ts b/packages/sheets-table/src/facade/f-worksheet.tsindex 59c1e80aa6..7c05819a2c 100644--- a/packages/sheets-table/src/facade/f-worksheet.ts+++ b/packages/sheets-table/src/facade/f-worksheet.ts@@ -25,7 +25,7 @@ import type {ITableOptions,ITableRange,} from '@univerjs/sheets-table';-import { cellToRange, Rectangle } from '@univerjs/core';+import { cellToRange, customNameCharacterCheck, ILogService, LocaleService, Rectangle } from '@univerjs/core';import { RangeThemeStyle } from '@univerjs/sheets';import {AddSheetTableCommand,@@ -70,7 +70,7 @@ export interface IFWorkSheetTableMixin {* }* ```*/- addTable(tableName: string, rangeInfo: ITableRange, tableId?: string, options?: ITableOptions): Promise<boolean>;+ addTable(tableName: string, rangeInfo: ITableRange, tableId?: string, options?: ITableOptions): Promise<boolean> | boolean;/*** Set the filter for a table column@@ -198,7 +198,7 @@ export interface IFWorkSheetTableMixin {* }* ```*/- setTableName(tableId: string, tableName: string): Promise<boolean>;+ setTableName(tableId: string, tableName: string): Promise<boolean> | boolean;/*** Get the list of tables in the worksheet@@ -332,9 +332,25 @@ export interface IFWorkSheetTableMixin {}export class FWorkSheetTableMixin extends FWorksheet implements IFWorkSheetTableMixin {- override addTable(tableName: string, rangeInfo: ITableRange, tableId?: string, options?: ITableOptions): Promise<boolean> {+ override addTable(tableName: string, rangeInfo: ITableRange, tableId?: string, options?: ITableOptions): Promise<boolean> | boolean {const subUnitId = this.getSheetId();- const unitId = this.getWorkbook().getUnitId();+ const workbook = this.getWorkbook();+ const unitId = workbook.getUnitId();++ const localeService = this._injector.get(LocaleService);++ const sheetNameSet = new Set<string>();+ if (workbook) {+ workbook.getSheets().forEach((sheet) => {+ sheetNameSet.add(sheet.getName());+ });+ }+ const isValidName = customNameCharacterCheck(tableName, sheetNameSet);+ if (!isValidName) {+ const logService = this._injector.get(ILogService);+ logService.warn(localeService.t('sheets-table.tableNameError'));+ return false;+ }const addTableParams: IAddSheetTableCommandParams = {unitId,subUnitId,@@ -376,7 +392,24 @@ export class FWorkSheetTableMixin extends FWorksheet implements IFWorkSheetTablereturn this._commandService.executeCommand(SetSheetTableCommand.id, tableSetConfig);}- override setTableName(tableId: string, tableName: string): Promise<boolean> {+ override setTableName(tableId: string, tableName: string): Promise<boolean> | boolean {+ const workbook = this.getWorkbook();++ const localeService = this._injector.get(LocaleService);++ const sheetNameSet = new Set<string>();+ if (workbook) {+ workbook.getSheets().forEach((sheet) => {+ sheetNameSet.add(sheet.getName());+ });+ }+ const isValidName = customNameCharacterCheck(tableName, sheetNameSet);+ if (!isValidName) {+ const logService = this._injector.get(ILogService);+ logService.warn(localeService.t('sheets-table.tableNameError'));+ return false;+ }+const tableSetConfig: ISetSheetTableCommandParams = {unitId: this.getWorkbook().getUnitId(),tableId,diff --git a/packages/sheets-table/src/model/table-manager.ts b/packages/sheets-table/src/model/table-manager.tsindex c1f3ac4d9a..9407855e35 100644--- a/packages/sheets-table/src/model/table-manager.ts+++ b/packages/sheets-table/src/model/table-manager.ts@@ -378,9 +378,23 @@ export class TableManager extends Disposable {unitMap.forEach((table) => {const subUnitId = table.getSubunitId();if (!result[subUnitId]) {- result[subUnitId] = [] as ITableJson[];+ const tableFilteredOutRows = new Set<number>();+ const tables = this.getTablesBySubunitId(unitId, subUnitId);+ tables.forEach((table) => {+ const tableFilteredRows = table.getTableFilters().getFilterOutRows();+ if (!tableFilteredRows) {+ return;+ }+ for (const row of tableFilteredRows) {+ tableFilteredOutRows.add(row);+ }+ });+ result[subUnitId] = {+ tables: [] as ITableJson[],+ tableFilteredOutRows: Array.from(tableFilteredOutRows),+ };}- result[subUnitId].push(table.toJSON());+ result[subUnitId].tables.push(table.toJSON());});}return result;@@ -395,7 +409,17 @@ export class TableManager extends Disposable {return;}const sheet = target.worksheet;- const tables = data[subUnitId];+ let tables;+ // adjust code for older data structures+ if (data[subUnitId].tables) {+ tables = data[subUnitId].tables;+ } else if (Array.isArray(data[subUnitId])) {+ // for older versions, where tables were not nested under subUnitId+ tables = data[subUnitId] as any as ITableJson[];+ }+ if (!tables) {+ return;+ }tables.forEach((table) => {const header = this.getColumnHeader(unitId, subUnitId, table.range);const tableInstance = new Table(table.id, table.name, table.range, header, table.options);diff --git a/packages/sheets-table/src/types/type.ts b/packages/sheets-table/src/types/type.tsindex bbbfb3fc3a..b83009031e 100644--- a/packages/sheets-table/src/types/type.ts+++ b/packages/sheets-table/src/types/type.ts@@ -194,7 +194,13 @@ export interface ITableInfoWithUnitId extends ITableInfo {}export interface ITableResource {- [subUnitId: string]: ITableJson[];+ [subUnitId: string]: {+ tables: ITableJson[];+ /**+ * The rows that are filtered out by the table filter+ */+ tableFilteredOutRows: number[];+ };}export interface ITableRelationItem {diff --git a/packages/sheets-table/src/util.ts b/packages/sheets-table/src/util.tsindex 030378d32d..3c95d77e60 100644--- a/packages/sheets-table/src/util.ts+++ b/packages/sheets-table/src/util.ts@@ -62,7 +62,7 @@ export function convertCellDataToString(cellData: Nullable<ICellData>): string {}export function getTableFilterState(tableFilter: ITableFilterItem | undefined, sortState: SheetsTableSortStateEnum): SheetsTableButtonStateEnum {- const hasFilter = tableFilter !== undefined;+ const hasFilter = tableFilter !== undefined && tableFilter !== null;if (hasFilter) {switch (sortState) {case SheetsTableSortStateEnum.Asc: