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.

fix(sheet): keep text formatting when setting range value (#2711)

Dushusira1a3dbcd829d
diff --git a/packages/engine-numfmt/src/const.ts b/packages/engine-numfmt/src/const.ts
new file mode 100644
index 0000000000..b74e897116
--- /dev/null
+++ b/packages/engine-numfmt/src/const.ts
@@ -0,0 +1,17 @@
+/**
+ * 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.
+ */
+
+export const DEFAULT_TEXT_FORMAT = '@@@';
diff --git a/packages/engine-numfmt/src/index.ts b/packages/engine-numfmt/src/index.ts
index fbae1c18db..02c2ec5f84 100644
--- a/packages/engine-numfmt/src/index.ts
+++ b/packages/engine-numfmt/src/index.ts
@@ -19,4 +19,6 @@ import numfmt from 'numfmt';
import type { Numfmt } from './type';
+export { DEFAULT_TEXT_FORMAT } from './const';
+
export default numfmt as Numfmt;
diff --git a/packages/sheets-numfmt/src/base/const/MENU-OPTIONS.ts b/packages/sheets-numfmt/src/base/const/MENU-OPTIONS.ts
index b39004faaf..9dc2e3ddb2 100644
--- a/packages/sheets-numfmt/src/base/const/MENU-OPTIONS.ts
+++ b/packages/sheets-numfmt/src/base/const/MENU-OPTIONS.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import { DEFAULT_TEXT_FORMAT } from '@univerjs/engine-numfmt';
+
export const MENU_OPTIONS: Array<{ label: string; pattern: string | null } | '|'> = [
{
label: 'sheet.numfmt.general',
@@ -21,7 +23,7 @@ export const MENU_OPTIONS: Array<{ label: string; pattern: string | null } | '|'
},
{
label: 'sheet.numfmt.text',
- pattern: '@@@',
+ pattern: DEFAULT_TEXT_FORMAT,
},
'|',
{
diff --git a/packages/sheets/src/basics/__tests__/cell-type.spec.ts b/packages/sheets/src/basics/__tests__/cell-type.spec.ts
new file mode 100644
index 0000000000..e1fd793ad4
--- /dev/null
+++ b/packages/sheets/src/basics/__tests__/cell-type.spec.ts
@@ -0,0 +1,39 @@
+/**
+ * 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 { describe, expect, it } from 'vitest';
+import { CellValueType } from '@univerjs/core';
+import { checkCellValueType } from '../cell-type';
+
+describe('test util cell type ', () => {
+ it('should be able to get the correct type of cell value from "checkCellValueType"', () => {
+ expect(checkCellValueType('string', CellValueType.BOOLEAN)).toBe(CellValueType.STRING);
+ expect(checkCellValueType('string', CellValueType.NUMBER)).toBe(CellValueType.STRING);
+ expect(checkCellValueType('string', CellValueType.STRING)).toBe(CellValueType.STRING);
+ expect(checkCellValueType('0', CellValueType.STRING)).toBe(CellValueType.NUMBER);
+ expect(checkCellValueType('true', CellValueType.STRING)).toBe(CellValueType.BOOLEAN);
+ expect(checkCellValueType('false', CellValueType.STRING)).toBe(CellValueType.BOOLEAN);
+
+ expect(checkCellValueType(123, CellValueType.STRING)).toBe(CellValueType.NUMBER);
+ expect(checkCellValueType(123, CellValueType.BOOLEAN)).toBe(CellValueType.NUMBER); // not a valid boolean number, casted to number
+ expect(checkCellValueType(123, CellValueType.NUMBER)).toBe(CellValueType.NUMBER);
+ expect(checkCellValueType(1, CellValueType.NUMBER)).toBe(CellValueType.NUMBER);
+ expect(checkCellValueType(0, CellValueType.NUMBER)).toBe(CellValueType.NUMBER);
+
+ expect(checkCellValueType(1, CellValueType.BOOLEAN)).toBe(CellValueType.BOOLEAN); // it is valid boolean value
+ expect(checkCellValueType(0, CellValueType.BOOLEAN)).toBe(CellValueType.BOOLEAN); // it is valid boolean value
+ });
+});
diff --git a/packages/sheets/src/basics/__tests__/cell-value.spec.ts b/packages/sheets/src/basics/__tests__/cell-value.spec.ts
new file mode 100644
index 0000000000..f571342f45
--- /dev/null
+++ b/packages/sheets/src/basics/__tests__/cell-value.spec.ts
@@ -0,0 +1,32 @@
+/**
+ * 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 { describe, expect, it } from 'vitest';
+import { extractBooleanValue } from '../cell-value';
+
+describe('test utils cell value', () => {
+ it('should be able to cast values that can be casted to boolean', () => {
+ expect(extractBooleanValue(1)).toBe(true);
+ expect(extractBooleanValue(0)).toBe(false);
+ expect(extractBooleanValue(-123)).toBe(null);
+ expect(extractBooleanValue('1')).toBe(true);
+ expect(extractBooleanValue('0')).toBe(false);
+ expect(extractBooleanValue('89757')).toBe(null);
+ expect(extractBooleanValue('true')).toBe(true);
+ expect(extractBooleanValue('false')).toBe(false);
+ expect(extractBooleanValue('Michael Jackson')).toBe(null);
+ });
+});
diff --git a/packages/sheets/src/basics/cell-style.ts b/packages/sheets/src/basics/cell-style.ts
new file mode 100644
index 0000000000..25e775a3e1
--- /dev/null
+++ b/packages/sheets/src/basics/cell-style.ts
@@ -0,0 +1,242 @@
+/**
+ * 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 { IBorderData, ICellData, IDocumentData, IKeyValue, IParagraph, IStyleData, ITextRun, ITextStyle, Nullable, Styles } from '@univerjs/core';
+import { normalizeTextRuns, Tools } from '@univerjs/core';
+
+export function handleStyle(styles: Styles, oldVal: ICellData, newVal: ICellData) {
+ // use null to clear style
+ const oldStyle = styles.getStyleByCell(oldVal);
+
+ if (oldStyle == null) {
+ // clear
+ delete oldVal.s;
+ }
+
+ if (typeof newVal.s === 'string') {
+ newVal.s = styles.get(newVal.s);
+ }
+
+ // set style
+ const merge = mergeStyle(oldStyle, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
+
+ // then remove null
+ merge && Tools.removeNull(merge);
+
+ if (Tools.isEmptyObject(merge)) {
+ delete oldVal.s;
+ } else {
+ oldVal.s = styles.setValue(merge);
+ }
+
+ const newValueStream = newVal.v ? `${newVal.v}\r\n` : '';
+ // Only need to copy newValue.s to oldValue.p when you modify the cell style, not when you modify the cell value.
+ if (!newVal.p && oldVal.p) {
+ if (newValueStream && newValueStream !== oldVal.p.body?.dataStream) {
+ delete oldVal.p;
+ } else {
+ mergeRichTextStyle(oldVal.p, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
+ }
+ }
+}
+
+/**
+ * Convert old style data for storage
+ * @param style
+ */
+export function transformStyle(oldStyle: Nullable<IStyleData>, newStyle: Nullable<IStyleData>): Nullable<IStyleData> {
+ const backupStyle = transformNormalKey(oldStyle, newStyle);
+ return backupStyle;
+}
+/**
+ * Convert old style normal key for storage
+ * @param style
+ */
+function transformNormalKey(
+ oldStyle: Nullable<IStyleData>,
+ newStyle: Nullable<IStyleData>
+): Nullable<IStyleData> {
+ // If there is no newly set style, directly store the historical style
+ if (!newStyle || !Object.keys(newStyle).length) {
+ return oldStyle;
+ }
+ const backupStyle: Record<string, any> = oldStyle || {};
+
+ for (const k in newStyle) {
+ if (k === 'bd') {
+ backupStyle[k] = transformBorders(backupStyle[k] || {}, newStyle[k]);
+ }
+ // 1. To modify the existing style,we need original setting to undo
+ // 2. Newly set the style, we need null to undo
+ else if (!(k in backupStyle)) {
+ backupStyle[k] = null;
+ }
+ }
+ return backupStyle;
+}
+
+/**
+ * Convert old style border for storage
+ * @param style
+ */
+function transformBorders(oldBorders: IBorderData, newBorders: Nullable<IBorderData>): IBorderData {
+ // If there is no newly set border, directly store the historical border
+ if (!newBorders || !Object.keys(newBorders).length) {
+ return oldBorders;
+ }
+
+ for (const k in newBorders) {
+ // 1. To modify the existing border,we need original setting to undo
+ // 2. Newly set the border, we need null to undo
+ if (!(k in oldBorders)) {
+ (oldBorders as IKeyValue)[k] = null;
+ }
+ }
+
+ return oldBorders;
+}
+
+/**
+ * merge new style to old style
+ * @param oldStyle
+ * @param newStyle
+ */
+function mergeStyle(
+ oldStyle: Nullable<IStyleData>,
+ newStyle: Nullable<IStyleData>,
+ isRichText: boolean = false
+): Nullable<IStyleData> {
+ // clear style
+ if (newStyle === null) return newStyle;
+ // don't operate
+ if (newStyle === undefined) return oldStyle;
+
+ const backupStyle: Record<string, any> = Tools.deepClone(oldStyle) || {};
+ if (!backupStyle) return;
+ for (const k in newStyle) {
+ if (isRichText && ['bd', 'tr', 'td', 'ht', 'vt', 'tb', 'pd'].includes(k)) {
+ continue;
+ }
+ // you can only choose one of the themeColor and rgbColor of the border setting
+ if (k in backupStyle && k === 'bd') {
+ backupStyle[k] = Object.assign(backupStyle[k], newStyle[k]);
+ } else {
+ backupStyle[k] = (newStyle as IKeyValue)[k];
+ }
+ }
+
+ if ('cl' in backupStyle) {
+ if ('ul' in backupStyle && backupStyle.ul) {
+ backupStyle.ul.cl = backupStyle.cl;
+ }
+
+ if ('ol' in backupStyle && backupStyle.ol) {
+ backupStyle.ol.cl = backupStyle.cl;
+ }
+
+ if ('st' in backupStyle && backupStyle.st) {
+ backupStyle.st.cl = backupStyle.cl;
+ }
+ }
+
+ return backupStyle;
+}
+
+function skipParagraphs(paragraphs: IParagraph[], offset: number): number {
+ if (paragraphs.some((p) => p.startIndex === offset)) {
+ return skipParagraphs(paragraphs, offset + 1);
+ }
+
+ return offset;
+}
+
+/**
+ * Find the text style of all paragraphs and modify it to the new style
+ * @param p
+ * @param newStyle
+ */
+function mergeRichTextStyle(p: IDocumentData, newStyle: Nullable<IStyleData>) {
+ if (p.body == null) {
+ return;
+ }
+
+ if (!Array.isArray(p.body.textRuns)) {
+ p.body.textRuns = [];
+ }
+
+ let index = 0;
+ const newTextRuns = [];
+ const paragraphs = p.body?.paragraphs || [];
+
+ for (const textRun of p.body.textRuns) {
+ const { st, ed, ts = {} } = textRun;
+
+ if (index < st) {
+ const tr: ITextRun = {
+ st: index,
+ ed: st,
+ };
+
+ const merge = mergeStyle({}, newStyle, true);
+
+ // then remove null
+ merge && Tools.removeNull(merge);
+
+ if (!Tools.isEmptyObject(merge)) {
+ tr.ts = merge!;
+ }
+
+ newTextRuns.push(tr);
+ }
+
+ const merge = mergeStyle(ts, newStyle, true);
+
+ // then remove null
+ merge && Tools.removeNull(merge);
+
+ if (Tools.isEmptyObject(merge)) {
+ delete textRun.ts;
+ } else {
+ textRun.ts = merge as ITextStyle;
+ }
+
+ newTextRuns.push(textRun);
+
+ index = skipParagraphs(paragraphs, ed);
+ }
+
+ const endIndex = p.body.dataStream.endsWith('\r\n') ? p.body.dataStream.length - 2 : p.body.dataStream.length;
+
+ if (index < endIndex) {
+ const tr: ITextRun = {
+ st: index,
+ ed: endIndex,
+ };
+
+ const merge = mergeStyle({}, newStyle, true);
+
+ // then remove null
+ merge && Tools.removeNull(merge);
+
+ if (!Tools.isEmptyObject(merge)) {
+ tr.ts = merge!;
+ }
+
+ newTextRuns.push(tr);
+ }
+
+ p.body.textRuns = normalizeTextRuns(newTextRuns);
+}
diff --git a/packages/sheets/src/basics/cell-type.ts b/packages/sheets/src/basics/cell-type.ts
new file mode 100644
index 0000000000..ccc50ce4c2
--- /dev/null
+++ b/packages/sheets/src/basics/cell-type.ts
@@ -0,0 +1,127 @@
+/**
+ * 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 { CellValue, ICellData, IStyleData, Nullable, Styles } from '@univerjs/core';
+import { CellValueType, isBooleanString, isRealNum } from '@univerjs/core';
+import { DEFAULT_TEXT_FORMAT } from '@univerjs/engine-numfmt';
+
+/**
+ * Get cell value type by style, new value and old value.
+ * If the new value contains t, then take t directly. In other cases, we need to dynamically determine based on actual data and styles
+ * @param newVal
+ * @param oldVal
+ * @returns
+ */
+export function getCellType(styles: Styles, newVal: ICellData, oldVal: ICellData) {
+ if (newVal.t) return newVal.t;
+ if (newVal.v === null) return null;
+
+ const newStyle = styles.getStyleByCell(newVal);
+ const oldStyle = styles.getStyleByCell(oldVal);
+
+ if (oldVal.t === CellValueType.FORCE_STRING) {
+ // For cells with forced strings, set the percentage format and still use forced strings
+ // For cells with forced strings, update to the number and convert to ordinary numbers
+ // For cells with forced strings and text formats, update to the number and still use forced strings
+ if (!isTextFormat(oldStyle) && newVal.v !== undefined) {
+ if (isRealNum(newVal.v)) {
+ return CellValueType.NUMBER;
+ } else if (isBooleanString(`${newVal.v}`)) {
+ return CellValueType.BOOLEAN;
+ }
+ }
+
+ return CellValueType.FORCE_STRING;
+ }
+
+ // For cells with ordinary numbers, set the text format and convert the cell type to text
+ if (hasNumberFormat(newStyle)) {
+ if (isTextFormat(newStyle)) {
+ return CellValueType.STRING;
+ }
+
+ return checkCellValueTypeByValue(newVal, oldVal);
+ }
+
+ // For cells with text format, the cell type is still text when numbers are written, because the ISNUMBER function detects FALSE
+ if (isTextFormat(oldStyle)) {
+ return CellValueType.STRING;
+ }
+
+ return checkCellValueTypeByValue(newVal, oldVal);
+}
+
+function checkCellValueTypeByValue(newVal: ICellData, oldVal: ICellData): Nullable<CellValueType> {
+ return newVal.v !== undefined ? checkCellValueType(newVal.v, newVal.t) : checkCellValueType(oldVal.v, oldVal.t);
+}
+
+function hasNumberFormat(style: Nullable<IStyleData>) {
+ return !!style?.n?.pattern;
+}
+
+function isTextFormat(style: Nullable<IStyleData>) {
+ return style?.n?.pattern === DEFAULT_TEXT_FORMAT;
+}
+
+/**
+ * Get the correct type after setting values to a cell.
+ *
+ * @param v the new value
+ * @param type the old type
+ * @returns the new type
+ */
+export function checkCellValueType(v: Nullable<CellValue>, type: Nullable<CellValueType>): Nullable<CellValueType> {
+ if (v === null) return null;
+
+ if (typeof v === 'string') {
+ // Support scientific notation, such as 10e+1
+ if (isRealNum(v)) {
+ if ((+v === 0 || +v === 1) && type === CellValueType.BOOLEAN) {
+ return CellValueType.BOOLEAN;
+ }
+
+ return CellValueType.NUMBER;
+ } else if (isBooleanString(v)) {
+ return CellValueType.BOOLEAN;
+ }
+ return CellValueType.STRING;
+ }
+
+ if (typeof v === 'number') {
+ if ((v === 0 || v === 1) && type === CellValueType.BOOLEAN) {
+ return CellValueType.BOOLEAN;
+ }
+ return CellValueType.NUMBER;
+ }
+
+ if (typeof v === 'boolean') {
+ return CellValueType.BOOLEAN;
+ }
+
+ return CellValueType.FORCE_STRING;
+}
+
+export function getCellTypeByPattern(cell: ICellData, pattern: string) {
+ if (cell.t === CellValueType.FORCE_STRING) {
+ return CellValueType.FORCE_STRING;
+ }
+
+ if (pattern === DEFAULT_TEXT_FORMAT) {
+ return CellValueType.STRING;
+ }
+
+ return checkCellValueType(cell.v, cell.t);
+}
diff --git a/packages/sheets/src/basics/cell-value.ts b/packages/sheets/src/basics/cell-value.ts
new file mode 100644
index 0000000000..d64208e9dd
--- /dev/null
+++ b/packages/sheets/src/basics/cell-value.ts
@@ -0,0 +1,123 @@
+/**
+ * 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 } from '@univerjs/core';
+import { CellValueType, isSafeNumeric } from '@univerjs/core';
+
+/**
+ * Get cell value from new value by type
+ * @param type
+ * @param cell
+ * @returns
+ */
+export function getCellValue(type: Nullable<CellValueType>, cell: ICellData) {
+ if (type === CellValueType.NUMBER) {
+ return Number(cell.v);
+ }
+
+ if (type === CellValueType.BOOLEAN) {
+ return extractBooleanValue(cell.v) ? 1 : 0;
+ }
+
+ if (type === CellValueType.STRING || type === CellValueType.FORCE_STRING) {
+ return `${cell.v}`;
+ }
+
+ return cell.v;
+}
+
+/**
+ * Check if the value can be casted to a boolean.
+ * @internal
+ * @param value
+ * @returns It would return null if the value cannot be casted to a boolean, and would return the boolean value if it can be casted.
+ */
+export function extractBooleanValue(value: Nullable<string | number | boolean>): Nullable<boolean> {
+ if (typeof value === 'string') {
+ if (value.toUpperCase() === 'TRUE') {
+ return true;
+ };
+
+ if (value.toUpperCase() === 'FALSE') {
+ return false;
+ }
+
+ if (isSafeNumeric(value)) {
+ if (Number(value) === 0) {
+ return false;
+ }
+
+ if (Number(value) === 1) {
+ return true;
+ }
+ }
+ }
+
+ if (typeof value === 'number') {
+ if (value === 0) {
+ return false;
+ }
+
+ if (value === 1) {
+ return true;
+ }
+ }
+
+ if (typeof value === 'boolean') {
+ return value;
+ }
+
+ return null;
+}
+
+/**
+ * Supplement the data of the cell, set the other value to NULL, Used to reset properties when undoing
+ * @param value
+ * @returns
+ */
+export function setNull(value: Nullable<ICellData>) {
+ if (value == null) return null;
+
+ if (value.f === undefined) {
+ value.f = null;
+ }
+
+ if (value.si === undefined) {
+ value.si = null;
+ }
+
+ if (value.p === undefined) {
+ value.p = null;
+ }
+
+ if (value.v === undefined) {
+ value.v = null;
+ }
+
+ if (value.t === undefined) {
+ value.t = null;
+ }
+
+ if (value.s === undefined) {
+ value.s = null;
+ }
+
+ if (value.custom === undefined) {
+ value.custom = null;
+ }
+
+ return value;
+}
diff --git a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
index d73ffa2537..3d18bc6b04 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
@@ -30,6 +30,7 @@ import {
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DEFAULT_TEXT_FORMAT } from '@univerjs/engine-numfmt';
import { SheetsSelectionsService } from '../../../services/selections/selection-manager.service';
import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
import type { ISetRangeValuesCommandParams } from '../set-range-values.command';
@@ -51,6 +52,34 @@ const getTestWorkbookDataDemo = (): IWorkbookData => ({
1: {
v: 'A2',
},
+ 2: {
+ s: 's5',
+ },
+ 3: {
+ s: 's5',
+ },
+ 5: {
+ v: 1,
+ t: CellValueType.NUMBER,
+ },
+ 6: {
+ v: '001',
+ t: CellValueType.STRING,
+ s: 's5',
+ },
+ 7: {
+ v: 'text',
+ t: CellValueType.STRING,
+ },
+ 8: {
+ v: '001',
+ t: CellValueType.FORCE_STRING,
+ },
+ 9: {
+ v: '001',
+ t: CellValueType.FORCE_STRING,
+ s: 's5',
+ },
},
1: {},
2: {
@@ -94,6 +123,11 @@ const getTestWorkbookDataDemo = (): IWorkbookData => ({
s2: { bl: 0 },
s3: { bl: 1 },
s4: { fs: 12 },
+ s5: {
+ n: {
+ pattern: DEFAULT_TEXT_FORMAT, // text
+ },
+ },
},
});
@@ -110,6 +144,10 @@ describe('Test set range values commands', () => {
endColumn: number
) => Nullable<Array<Array<Nullable<ICellData>>>>;
let getStyle: () => any;
+ let getStyles: (startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number) => Nullable<Nullable<IStyleData>[][]>;
beforeEach(() => {
const testBed = createCommandTestBed(getTestWorkbookDataDemo());
@@ -155,6 +193,20 @@ describe('Test set range values commands', () => {
return styles.getStyleByCell(value);
}
};
+
+ getStyles = (startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number): Nullable<Nullable<IStyleData>[][]> => {
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();
+
+ return values?.map((row, rowIndex) => {
+ return row?.map((cell, columnIndex) => {
+ return cell && styles?.getStyleByCell(cell);
+ });
+ });
+ };
});
afterEach(() => {
@@ -697,6 +749,282 @@ describe('Test set range values commands', () => {
})).toBeTruthy();
expect(getValue()?.p).toBeTruthy();
});
+
+ it('set value when origin cell has text number format', async () => {
+ function getParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 2: { v: '01' }, 3: { v: '0.20' }, 4: { v: '001', t: CellValueType.FORCE_STRING }, 5: { s: { n: { pattern: DEFAULT_TEXT_FORMAT } } } } },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getParams())).toBeTruthy();
+ expect(getValues(0, 2, 0, 5)).toStrictEqual([[{ s: 's5', v: '01', t: CellValueType.STRING }, { s: 's5', v: '0.20', t: CellValueType.STRING }, { v: '001', t: CellValueType.FORCE_STRING }, { s: 's5', v: '1', t: CellValueType.STRING }]]);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 2, 0, 5)).toStrictEqual([[{ s: 's5' }, { s: 's5' }, {}, { v: 1, t: CellValueType.NUMBER }]]);
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValues(0, 2, 0, 5)).toStrictEqual([[{ s: 's5', v: '01', t: CellValueType.STRING }, { s: 's5', v: '0.20', t: CellValueType.STRING }, { v: '001', t: CellValueType.FORCE_STRING }, { s: 's5', v: '1', t: CellValueType.STRING }]]);
+ });
+
+ it('set value when origin cell has number in text format, set new number format', async () => {
+ function getParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 6: { s: { n: { pattern: '0%' } } } } },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getParams())).toBeTruthy();
+
+ const newValue = getValues(0, 6, 0, 6);
+ const styles = getStyles(0, 6, 0, 6);
+
+ expect(styles).toStrictEqual([[{ n: { pattern: '0%' } }]]);
+
+ delete newValue?.[0][0]?.s;
+ expect(newValue).toStrictEqual([[{
+ v: 1,
+ t: CellValueType.NUMBER,
+ }]]);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 6, 0, 6)).toStrictEqual([[{ v: '001', t: CellValueType.STRING, s: 's5' }]]);
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+
+ const redoNewValue = getValues(0, 6, 0, 6);
+ const redoStyles = getStyles(0, 6, 0, 6);
+
+ expect(redoStyles).toStrictEqual([[{ n: { pattern: '0%' } }]]);
+
+ delete redoNewValue?.[0][0]?.s;
+ expect(redoNewValue).toStrictEqual([[{
+ v: 1,
+ t: CellValueType.NUMBER,
+ }]]);
+ });
+
+ it('set value when origin cell has text in text format, set new number format', async () => {
+ function getParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 7: { s: { n: { pattern: '0%' } } } } },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getParams())).toBeTruthy();
+
+ const newValue = getValues(0, 7, 0, 7);
+ const styles = getStyles(0, 7, 0, 7);
+
+ expect(styles).toStrictEqual([[{ n: { pattern: '0%' } }]]);
+
+ delete newValue?.[0][0]?.s;
+ expect(newValue).toStrictEqual([[{
+ v: 'text',
+ t: CellValueType.STRING,
+ }]]);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 7, 0, 7)).toStrictEqual([[{
+ v: 'text',
+ t: CellValueType.STRING,
+ }]]);
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+
+ const redoNewValue = getValues(0, 7, 0, 7);
+ const redoStyles = getStyles(0, 7, 0, 7);
+
+ expect(redoStyles).toStrictEqual([[{ n: { pattern: '0%' } }]]);
+
+ delete redoNewValue?.[0][0]?.s;
+ expect(redoNewValue).toStrictEqual([[{
+ v: 'text',
+ t: CellValueType.STRING,
+ }]]);
+ });
+
+ it('set value when origin cell has force string, set new number format', async () => {
+ function getParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 8: { s: { n: { pattern: '0%' } } } } },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getParams())).toBeTruthy();
+
+ const newValue = getValues(0, 8, 0, 8);
+ const styles = getStyles(0, 8, 0, 8);
+
+ expect(styles).toStrictEqual([[{ n: { pattern: '0%' } }]]);
+
+ delete newValue?.[0][0]?.s;
+ expect(newValue).toStrictEqual([[{
+ v: '001',
+ t: CellValueType.FORCE_STRING,
+ }]]);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 8, 0, 8)).toStrictEqual([[{ v: '001', t: CellValueType.FORCE_STRING }]]);
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+
+ const redoNewValue = getValues(0, 8, 0, 8);
+ const redoStyles = getStyles(0, 8, 0, 8);
+
+ expect(redoStyles).toStrictEqual([[{ n: { pattern: '0%' } }]]);
+
+ delete redoNewValue?.[0][0]?.s;
+ expect(redoNewValue).toStrictEqual([[{
+ v: '001',
+ t: CellValueType.FORCE_STRING,
+ }]]);
+ });
+
+ it('set value when origin cell has force string, set new number value', async () => {
+ function getParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 8: { v: '2' } } },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getParams())).toBeTruthy();
+
+ const newValue = getValues(0, 8, 0, 8);
+ expect(newValue).toStrictEqual([[{
+ v: 2,
+ t: CellValueType.NUMBER,
+ }]]);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 8, 0, 8)).toStrictEqual([[{ v: '001', t: CellValueType.FORCE_STRING }]]);
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+
+ const redoNewValue = getValues(0, 8, 0, 8);
+ expect(redoNewValue).toStrictEqual([[{
+ v: 2,
+ t: CellValueType.NUMBER,
+ }]]);
+ });
+
+ it('set value when origin cell has force string, set new boolean value', async () => {
+ function getParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 8: { v: 'true' } } },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getParams())).toBeTruthy();
+
+ const newValue = getValues(0, 8, 0, 8);
+ expect(newValue).toStrictEqual([[{
+ v: 1,
+ t: CellValueType.BOOLEAN,
+ }]]);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 8, 0, 8)).toStrictEqual([[{ v: '001', t: CellValueType.FORCE_STRING }]]);
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+
+ const redoNewValue = getValues(0, 8, 0, 8);
+ expect(redoNewValue).toStrictEqual([[{
+ v: 1,
+ t: CellValueType.BOOLEAN,
+ }]]);
+ });
+
+ it('set value when origin cell has force string and text number format, set new number value', async () => {
+ function getParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 9: { v: '2' } } },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getParams())).toBeTruthy();
+
+ const newValue = getValues(0, 9, 0, 9);
+ expect(newValue).toStrictEqual([[{ v: '2', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 9, 0, 9)).toStrictEqual([[{ v: '001', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+
+ const redoNewValue = getValues(0, 9, 0, 9);
+ expect(redoNewValue).toStrictEqual([[{ v: '2', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+ });
+
+ it('set value when origin cell has force string and text number format, set new boolean value', async () => {
+ function getFirstParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 9: { v: 'false' } } },
+ };
+
+ return params;
+ }
+
+ function getSecondParams() {
+ const params: ISetRangeValuesCommandParams = {
+ value: { 0: { 9: { v: 'true' } } },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getFirstParams())).toBeTruthy();
+
+ let newValue = getValues(0, 9, 0, 9);
+ expect(newValue).toStrictEqual([[{ v: 'false', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getSecondParams())).toBeTruthy();
+
+ newValue = getValues(0, 9, 0, 9);
+ expect(newValue).toStrictEqual([[{ v: 'true', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 9, 0, 9)).toStrictEqual([[{ v: 'false', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(0, 9, 0, 9)).toStrictEqual([[{ v: '001', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValues(0, 9, 0, 9)).toStrictEqual([[{ v: 'false', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValues(0, 9, 0, 9)).toStrictEqual([[{ v: 'true', t: CellValueType.FORCE_STRING, s: 's5' }]]);
+ });
});
describe('fault situations', () => {
diff --git a/packages/sheets/src/commands/mutations/__tests__/set-range-values.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/set-range-values.mutation.spec.ts
deleted file mode 100644
index 82a4810b75..0000000000
--- a/packages/sheets/src/commands/mutations/__tests__/set-range-values.mutation.spec.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * 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 { describe, expect, it } from 'vitest';
-import { CellValueType } from '@univerjs/core';
-import { checkCellValueType, extractBooleanValue } from '../set-range-values.mutation';
-
-describe('test "SetRangeValuesMutation" ', () => {
- describe('test type related utils', () => {
- it('should be able to get the correct type of cell value from "checkCellValueType"', () => {
- expect(checkCellValueType('string', CellValueType.BOOLEAN)).toBe(CellValueType.STRING);
- expect(checkCellValueType('string', CellValueType.NUMBER)).toBe(CellValueType.STRING);
- expect(checkCellValueType('string', CellValueType.STRING)).toBe(CellValueType.STRING);
- expect(checkCellValueType('0', CellValueType.STRING)).toBe(CellValueType.NUMBER);
- expect(checkCellValueType('true', CellValueType.STRING)).toBe(CellValueType.BOOLEAN);
- expect(checkCellValueType('false', CellValueType.STRING)).toBe(CellValueType.BOOLEAN);
-
- expect(checkCellValueType(123, CellValueType.STRING)).toBe(CellValueType.NUMBER);
- expect(checkCellValueType(123, CellValueType.BOOLEAN)).toBe(CellValueType.NUMBER); // not a valid boolean number, casted to number
- expect(checkCellValueType(123, CellValueType.NUMBER)).toBe(CellValueType.NUMBER);
- expect(checkCellValueType(1, CellValueType.NUMBER)).toBe(CellValueType.NUMBER);
- expect(checkCellValueType(0, CellValueType.NUMBER)).toBe(CellValueType.NUMBER);
-
- expect(checkCellValueType(1, CellValueType.BOOLEAN)).toBe(CellValueType.BOOLEAN); // it is valid boolean value
- expect(checkCellValueType(0, CellValueType.BOOLEAN)).toBe(CellValueType.BOOLEAN); // it is valid boolean value
-
- expect(checkCellValueType('2', CellValueType.FORCE_STRING)).toBe(CellValueType.FORCE_STRING); // do not change cell value type when it is force string
- });
-
- it('should be able to cast values that can be casted to boolean', () => {
- expect(extractBooleanValue(1)).toBe(true);
- expect(extractBooleanValue(0)).toBe(false);
- expect(extractBooleanValue(-123)).toBe(null);
- expect(extractBooleanValue('1')).toBe(true);
- expect(extractBooleanValue('0')).toBe(false);
- expect(extractBooleanValue('89757')).toBe(null);
- expect(extractBooleanValue('true')).toBe(true);
- expect(extractBooleanValue('false')).toBe(false);
- expect(extractBooleanValue('Michael Jackson')).toBe(null);
- });
- });
-});
diff --git a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
index 3eba109a04..12d8b40d8c 100644
--- a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -15,24 +15,20 @@
*/
import type {
- CellValue,
- IBorderData,
ICellData,
ICopyToOptionsData,
- IDocumentData,
- IKeyValue,
IMutation,
IMutationCommonParams,
IObjectMatrixPrimitiveType,
- IParagraph,
IRange,
- IStyleData,
- ITextRun,
- ITextStyle,
Nullable,
+ Workbook,
} from '@univerjs/core';
-import { CellValueType, CommandType, isBooleanString, isSafeNumeric, IUniverInstanceService, normalizeTextRuns, ObjectMatrix, Tools } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, ObjectMatrix, Tools } from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
+import { handleStyle, transformStyle } from '../../basics/cell-style';
+import { getCellValue, setNull } from '../../basics/cell-value';
+import { getCellType } from '../../basics/cell-type';
/** Params of `SetRangeValuesMutation` */
export interface ISetRangeValuesMutationParams extends IMutationCommonParams {
@@ -48,11 +44,6 @@ export interface ISetRangeValuesMutationParams extends IMutationCommonParams {
* @deprecated not a good design
*/
options?: ICopyToOptionsData;
-
- // /**
- // * for formula calculate
- // */
- // isFormulaUpdate?: boolean;
}
export interface ISetRangeValuesRangeMutationParams extends ISetRangeValuesMutationParams {
@@ -108,45 +99,6 @@ export const SetRangeValuesUndoMutationFactory = (
} as ISetRangeValuesMutationParams;
};
-/**
- * Supplement the data of the cell, set the other value to NULL, Used to reset properties when undoing
- * @param value
- * @returns
- */
-function setNull(value: Nullable<ICellData>) {
- if (value == null) return null;
-
- if (value.f === undefined) {
- value.f = null;
- }
-
- if (value.si === undefined) {
- value.si = null;
- }
-
- if (value.p === undefined) {
- value.p = null;
- }
-
- if (value.v === undefined) {
- value.v = null;
- }
-
- if (value.t === undefined) {
- value.t = null;
- }
-
- if (value.s === undefined) {
- value.s = null;
- }
-
- if (value.custom === undefined) {
- value.custom = null;
- }
-
- return value;
-}
-
/**
* TODO@Dushusir: Excel can display numbers with up to about 15 digits of precision. When the user inputs more than 15 digits, interception is required, but there are unknown performance risks.
@@ -157,11 +109,10 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
type: CommandType.MUTATION,
- // eslint-disable-next-line max-lines-per-function
handler: (accessor, params) => {
const { cellValue, subUnitId, unitId } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
- const workbook = univerInstanceService.getUniverSheetInstance(unitId);
+ const workbook = univerInstanceService.getUnit<Workbook>(unitId);
if (!workbook) {
return false;
}
@@ -175,7 +126,6 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
const styles = workbook.getStyles();
const newValues = new ObjectMatrix(cellValue);
- // eslint-disable-next-line complexity
newValues.forValue((row, col, newVal) => {
// clear all
if (!newVal) {
@@ -184,12 +134,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
const oldVal = cellMatrix.getValue(row, col) || {};
// NOTE: we may need to take `p` into account
- // If the new value contains t, then take t directly
- const type = newVal.t
- ? newVal.t
- : newVal.v !== undefined
- ? checkCellValueType(newVal.v, newVal.t)
- : checkCellValueType(oldVal.v, oldVal.t);
+ const type = getCellType(styles, newVal, oldVal);
if (newVal.f !== undefined) {
oldVal.f = newVal.f;
@@ -205,52 +150,18 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
// Set to null, clear content
if (newVal.v !== undefined) {
- oldVal.v = type === CellValueType.NUMBER
- ? Number(newVal.v)
- : type === CellValueType.BOOLEAN
- ? extractBooleanValue(newVal.v) ? 1 : 0
- : newVal.v;
+ oldVal.v = getCellValue(type, newVal);
}
if (oldVal.v !== undefined) {
oldVal.t = type;
+ // The text format may be set for the numeric cell, and cell.v needs to be converted to text
+ oldVal.v = getCellValue(type, oldVal);
}
// handle style
if (newVal.s !== undefined) {
- // use null to clear style
- const oldStyle = styles.getStyleByCell(oldVal);
-
- if (oldStyle == null) {
- // clear
- delete oldVal.s;
- }
-
- if (typeof newVal.s === 'string') {
- newVal.s = styles.get(newVal.s);
- }
-
- // set style
- const merge = mergeStyle(oldStyle, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
-
- // then remove null
- merge && Tools.removeNull(merge);
-
- if (Tools.isEmptyObject(merge)) {
- delete oldVal.s;
- } else {
- oldVal.s = styles.setValue(merge);
- }
-
- const newValueStream = newVal.v ? `${newVal.v}\r\n` : '';
- // Only need to copy newValue.s to oldValue.p when you modify the cell style, not when you modify the cell value.
- if (!newVal.p && oldVal.p) {
- if (newValueStream && newValueStream !== oldVal.p.body?.dataStream) {
- delete oldVal.p;
- } else {
- mergeRichTextStyle(oldVal.p, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
- }
- }
+ handleStyle(styles, oldVal, newVal);
}
if (newVal.custom !== undefined) {
@@ -264,286 +175,3 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
return true;
},
};
-
-/**
- * Get the correct type after setting values to a cell.
- *
- * @param v the new value
- * @param oldType the old type
- * @returns the new type
- */
-export function checkCellValueType(v: Nullable<CellValue>, oldType: Nullable<CellValueType>): Nullable<CellValueType> {
- if (v === null) return null;
-
- if (oldType === CellValueType.FORCE_STRING) return oldType;
-
- if (typeof v === 'string') {
- if (isSafeNumeric(v)) {
- if ((+v === 0 || +v === 1) && oldType === CellValueType.BOOLEAN) {
- return CellValueType.BOOLEAN;
- }
-
- return CellValueType.NUMBER;
- } else if (isBooleanString(v)) {
- return CellValueType.BOOLEAN;
- }
- return CellValueType.STRING;
- }
-
- if (typeof v === 'number') {
- if ((v === 0 || v === 1) && oldType === CellValueType.BOOLEAN) {
- return CellValueType.BOOLEAN;
- }
- return CellValueType.NUMBER;
- }
-
- if (typeof v === 'boolean') {
- return CellValueType.BOOLEAN;
- }
-
- return CellValueType.FORCE_STRING;
-}
-
-/**
- * Check if the value can be casted to a boolean.
- * @internal
- * @param value
- * @returns It would return null if the value cannot be casted to a boolean, and would return the boolean value if it can be casted.
- */
-export function extractBooleanValue(value: Nullable<string | number | boolean>): Nullable<boolean> {
- if (typeof value === 'string') {
- if (value.toUpperCase() === 'TRUE') {
- return true;
- };
-
- if (value.toUpperCase() === 'FALSE') {
- return false;
- }
-
- if (isSafeNumeric(value)) {
- if (Number(value) === 0) {
- return false;
- }
-
- if (Number(value) === 1) {
- return true;
- }
- }
- }
-
- if (typeof value === 'number') {
- if (value === 0) {
- return false;
- }
-
- if (value === 1) {
- return true;
- }
- }
-
- if (typeof value === 'boolean') {
- return value;
- }
-
- return null;
-}
-
-/**
- * Convert old style data for storage
- * @param style
- */
-export function transformStyle(oldStyle: Nullable<IStyleData>, newStyle: Nullable<IStyleData>): Nullable<IStyleData> {
- const backupStyle = transformNormalKey(oldStyle, newStyle);
- return backupStyle;
-}
-/**
- * Convert old style normal key for storage
- *
- * @param style
- */
-export function transformNormalKey(
- oldStyle: Nullable<IStyleData>,
- newStyle: Nullable<IStyleData>
-): Nullable<IStyleData> {
- // If there is no newly set style, directly store the historical style
- if (!newStyle || !Object.keys(newStyle).length) {
- return oldStyle;
- }
- const backupStyle: Record<string, any> = oldStyle || {};
-
- for (const k in newStyle) {
- if (k === 'bd') {
- backupStyle[k] = transformBorders(backupStyle[k] || {}, newStyle[k]);
- }
- // 1. To modify the existing style,we need original setting to undo
- // 2. Newly set the style, we need null to undo
- else if (!(k in backupStyle)) {
- backupStyle[k] = null;
- }
- }
- return backupStyle;
-}
-/**
- * Convert old style border for storage
- *
-
- * @param style
- */
-export function transformBorders(oldBorders: IBorderData, newBorders: Nullable<IBorderData>): IBorderData {
- // If there is no newly set border, directly store the historical border
- if (!newBorders || !Object.keys(newBorders).length) {
- return oldBorders;
- }
-
- for (const k in newBorders) {
- // 1. To modify the existing border,we need original setting to undo
- // 2. Newly set the border, we need null to undo
- if (!(k in oldBorders)) {
- (oldBorders as IKeyValue)[k] = null;
- }
- }
-
- return oldBorders;
-}
-
-/**
- * merge new style to old style
- *
- * @param oldStyle
- * @param newStyle
- */
-export function mergeStyle(
- oldStyle: Nullable<IStyleData>,
- newStyle: Nullable<IStyleData>,
- isRichText: boolean = false
-): Nullable<IStyleData> {
- // clear style
- if (newStyle === null) return newStyle;
- // don't operate
- if (newStyle === undefined) return oldStyle;
-
- const backupStyle: Record<string, any> = Tools.deepClone(oldStyle) || {};
- if (!backupStyle) return;
- for (const k in newStyle) {
- if (isRichText && ['bd', 'tr', 'td', 'ht', 'vt', 'tb', 'pd'].includes(k)) {
- continue;
- }
- // you can only choose one of the themeColor and rgbColor of the border setting
- if (k in backupStyle && k === 'bd') {
- backupStyle[k] = Object.assign(backupStyle[k], newStyle[k]);
- } else {
- backupStyle[k] = (newStyle as IKeyValue)[k];
- }
- }
-
- // Overline/Strikethrough/Underline color follows text color
- // if ('cl' in backupStyle) {
- // for (const k in newStyle) {
- // if (['ul', 'ol', 'st'].includes(k)) {
- // backupStyle[k].cl = backupStyle.cl;
- // }
- // }
- // }
-
- if ('cl' in backupStyle) {
- if ('ul' in backupStyle && backupStyle.ul) {
- backupStyle.ul.cl = backupStyle.cl;
- }
-
- if ('ol' in backupStyle && backupStyle.ol) {
- backupStyle.ol.cl = backupStyle.cl;
- }
-
- if ('st' in backupStyle && backupStyle.st) {
- backupStyle.st.cl = backupStyle.cl;
- }
- }
-
- return backupStyle;
-}
-
-function skipParagraphs(paragraphs: IParagraph[], offset: number): number {
- if (paragraphs.some((p) => p.startIndex === offset)) {
- return skipParagraphs(paragraphs, offset + 1);
- }
-
- return offset;
-}
-
-/**
- * Find the text style of all paragraphs and modify it to the new style
- * @param p
- * @param newStyle
- */
-export function mergeRichTextStyle(p: IDocumentData, newStyle: Nullable<IStyleData>) {
- if (p.body == null) {
- return;
- }
-
- if (!Array.isArray(p.body.textRuns)) {
- p.body.textRuns = [];
- }
-
- let index = 0;
- const newTextRuns = [];
- const paragraphs = p.body?.paragraphs || [];
-
- for (const textRun of p.body.textRuns) {
- const { st, ed, ts = {} } = textRun;
-
- if (index < st) {
- const tr: ITextRun = {
- st: index,
- ed: st,
- };
-
- const merge = mergeStyle({}, newStyle, true);
-
- // then remove null
- merge && Tools.removeNull(merge);
-
- if (!Tools.isEmptyObject(merge)) {
- tr.ts = merge!;
- }
-
- newTextRuns.push(tr);
- }
-
- const merge = mergeStyle(ts, newStyle, true);
-
- // then remove null
- merge && Tools.removeNull(merge);
-
- if (Tools.isEmptyObject(merge)) {
- delete textRun.ts;
- } else {
- textRun.ts = merge as ITextStyle;
- }
-
- newTextRuns.push(textRun);
-
- index = skipParagraphs(paragraphs, ed);
- }
-
- const endIndex = p.body.dataStream.endsWith('\r\n') ? p.body.dataStream.length - 2 : p.body.dataStream.length;
-
- if (index < endIndex) {
- const tr: ITextRun = {
- st: index,
- ed: endIndex,
- };
-
- const merge = mergeStyle({}, newStyle, true);
-
- // then remove null
- merge && Tools.removeNull(merge);
-
- if (!Tools.isEmptyObject(merge)) {
- tr.ts = merge!;
- }
-
- newTextRuns.push(tr);
- }
-
- p.body.textRuns = normalizeTextRuns(newTextRuns);
-}
diff --git a/packages/sheets/src/services/__tests__/numfmt.service.test.ts b/packages/sheets/src/services/__tests__/numfmt.service.test.ts
index 5b0406c498..38eea230b7 100644
--- a/packages/sheets/src/services/__tests__/numfmt.service.test.ts
+++ b/packages/sheets/src/services/__tests__/numfmt.service.test.ts
@@ -14,12 +14,13 @@
* limitations under the License.
*/
-import type { Univer, Workbook } from '@univerjs/core';
-import { cellToRange, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import type { Styles, Univer, Workbook, Worksheet } from '@univerjs/core';
+import { cellToRange, CellValueType, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import type { IRemoveNumfmtMutationParams, ISetNumfmtMutationParams } from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DEFAULT_TEXT_FORMAT } from '@univerjs/engine-numfmt';
import { RemoveNumfmtMutation, SetNumfmtMutation } from '../../commands/mutations/numfmt-mutation';
import { NumfmtService } from '../numfmt/numfmt.service';
import { INumfmtService } from '../numfmt/type';
@@ -29,6 +30,13 @@ describe('test numfmt service', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
+ let univerInstanceService: IUniverInstanceService;
+ let numfmtService: INumfmtService;
+ let workbook: Workbook;
+ let styles: Styles;
+ let sheet: Worksheet;
+ let unitId: string;
+ let subUnitId: string;
beforeEach(() => {
const testBed = createTestBase(undefined, [[INumfmtService, { useClass: NumfmtService }]]);
@@ -37,6 +45,14 @@ describe('test numfmt service', () => {
commandService = get(ICommandService);
commandService.registerCommand(SetNumfmtMutation);
commandService.registerCommand(RemoveNumfmtMutation);
+
+ univerInstanceService = get(IUniverInstanceService);
+ numfmtService = get(INumfmtService);
+ workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ styles = workbook.getStyles();
+ sheet = workbook.getActiveSheet()!;
+ unitId = workbook.getUnitId();
+ subUnitId = sheet.getSheetId();
});
afterEach(() => {
@@ -44,12 +60,6 @@ describe('test numfmt service', () => {
});
it('model delete', () => {
- const univerInstanceService = get(IUniverInstanceService);
- const numfmtService = get(INumfmtService);
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
- const sheet = workbook.getActiveSheet()!;
- const unitId = workbook.getUnitId();
- const subUnitId = sheet.getSheetId();
const params: ISetNumfmtMutationParams = {
unitId,
subUnitId,
@@ -73,14 +83,7 @@ describe('test numfmt service', () => {
expect(numfmtValueDelete).toEqual(null);
});
- it('model set', () => {
- const univerInstanceService = get(IUniverInstanceService);
- const numfmtService = get(INumfmtService);
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
- const styles = workbook.getStyles();
- const sheet = workbook.getActiveSheet()!;
- const unitId = workbook.getUnitId();
- const subUnitId = sheet.getSheetId();
+ it('model set, normal format', () => {
const params: ISetNumfmtMutationParams = {
unitId,
subUnitId,
@@ -97,4 +100,88 @@ describe('test numfmt service', () => {
const numfmtId = sheet.getCellRaw(1, 1)?.s;
expect(styles.get(numfmtId)?.n).toEqual({ pattern: 'asdws' });
});
+
+ it('model set, update format', () => {
+ const params: ISetNumfmtMutationParams = {
+ unitId,
+ subUnitId,
+ refMap: {
+ 1: {
+ pattern: DEFAULT_TEXT_FORMAT,
+ },
+ },
+ values: { 1: { ranges: [cellToRange(0, 5)] } },
+ };
+ commandService.executeCommand(SetNumfmtMutation.id, params);
+ const numfmt = numfmtService.getValue(unitId, subUnitId, 0, 5);
+ expect(numfmt?.pattern).toEqual(DEFAULT_TEXT_FORMAT);
+
+ const cell = sheet.getCellRaw(0, 5);
+ const numfmtId = cell?.s;
+ expect(styles.get(numfmtId)?.n).toEqual({ pattern: DEFAULT_TEXT_FORMAT });
+ expect(cell).toStrictEqual({ v: '1', t: CellValueType.STRING, s: numfmtId });
+ });
+
+ it('model set, text format contains number, to number format', () => {
+ const params: ISetNumfmtMutationParams = {
+ unitId,
+ subUnitId,
+ refMap: {
+ 1: {
+ pattern: '0%',
+ },
+ },
+ values: { 1: { ranges: [cellToRange(0, 6)] } },
+ };
+ commandService.executeCommand(SetNumfmtMutation.id, params);
+ const numfmt = numfmtService.getValue(unitId, subUnitId, 0, 6);
+ expect(numfmt?.pattern).toEqual('0%');
+
+ const cell = sheet.getCellRaw(0, 6);
+ const numfmtId = cell?.s;
+ expect(styles.get(numfmtId)?.n).toEqual({ pattern: '0%' });
+ expect(cell).toStrictEqual({ v: 1, t: CellValueType.NUMBER, s: numfmtId });
+ });
+
+ it('model set, text format contains text, to number format', () => {
+ const params: ISetNumfmtMutationParams = {
+ unitId,
+ subUnitId,
+ refMap: {
+ 1: {
+ pattern: '0%',
+ },
+ },
+ values: { 1: { ranges: [cellToRange(0, 7)] } },
+ };
+ commandService.executeCommand(SetNumfmtMutation.id, params);
+ const numfmt = numfmtService.getValue(unitId, subUnitId, 0, 7);
+ expect(numfmt?.pattern).toEqual('0%');
+
+ const cell = sheet.getCellRaw(0, 7);
+ const numfmtId = cell?.s;
+ expect(styles.get(numfmtId)?.n).toEqual({ pattern: '0%' });
+ expect(cell).toStrictEqual({ v: 'text', t: CellValueType.STRING, s: numfmtId });
+ });
+
+ it('model set, force string, to number format', () => {
+ const params: ISetNumfmtMutationParams = {
+ unitId,
+ subUnitId,
+ refMap: {
+ 1: {
+ pattern: '0%',
+ },
+ },
+ values: { 1: { ranges: [cellToRange(0, 8)] } },
+ };
+ commandService.executeCommand(SetNumfmtMutation.id, params);
+ const numfmt = numfmtService.getValue(unitId, subUnitId, 0, 8);
+ expect(numfmt?.pattern).toEqual('0%');
+
+ const cell = sheet.getCellRaw(0, 8);
+ const numfmtId = cell?.s;
+ expect(styles.get(numfmtId)?.n).toEqual({ pattern: '0%' });
+ expect(cell).toStrictEqual({ v: '001', t: CellValueType.FORCE_STRING, s: numfmtId });
+ });
});
diff --git a/packages/sheets/src/services/__tests__/util.ts b/packages/sheets/src/services/__tests__/util.ts
index cb1ed3e5e6..8dda30c3e8 100644
--- a/packages/sheets/src/services/__tests__/util.ts
+++ b/packages/sheets/src/services/__tests__/util.ts
@@ -15,7 +15,8 @@
*/
import type { IWorkbookData } from '@univerjs/core';
-import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
+import { CellValueType, ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
+import { DEFAULT_TEXT_FORMAT } from '@univerjs/engine-numfmt';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
@@ -33,6 +34,23 @@ export const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
1: {
v: 'A2',
},
+ 5: {
+ v: 1,
+ t: CellValueType.NUMBER,
+ },
+ 6: {
+ v: '001',
+ t: CellValueType.STRING,
+ s: 's5',
+ },
+ 7: {
+ v: 'text',
+ t: CellValueType.STRING,
+ },
+ 8: {
+ v: '001',
+ t: CellValueType.FORCE_STRING,
+ },
},
},
},
@@ -53,7 +71,13 @@ export const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
locale: LocaleType.ZH_CN,
name: '',
sheetOrder: ['sheet1'],
- styles: {},
+ styles: {
+ s5: {
+ n: {
+ pattern: DEFAULT_TEXT_FORMAT, // text
+ },
+ },
+ },
};
export function createTestBase(workbookData?: IWorkbookData, dependencies?: Dependency[]) {
diff --git a/packages/sheets/src/services/numfmt/numfmt.service.ts b/packages/sheets/src/services/numfmt/numfmt.service.ts
index c4a8d728b4..a78a3f27f6 100644
--- a/packages/sheets/src/services/numfmt/numfmt.service.ts
+++ b/packages/sheets/src/services/numfmt/numfmt.service.ts
@@ -23,6 +23,8 @@ import {
Range,
} from '@univerjs/core';
+import { getCellTypeByPattern } from '../../basics/cell-type';
+import { getCellValue } from '../../basics/cell-value';
import type { INumfmtService } from './type';
export class NumfmtService extends Disposable implements INumfmtService {
@@ -106,10 +108,17 @@ export class NumfmtService extends Disposable implements INumfmtService {
const styleId = styles.setValue(style);
styleId && matrix.setValue(row, col, { s: styleId });
} else {
- const oldStyle = (cell.s && styles.get(cell.s)) || {};
+ const oldStyle = styles.getStyleByCell(cell) || {};
const newStyle = { ...oldStyle, n: { pattern: value.pattern } };
const styleId = styles.setValue(newStyle);
cell.s = styleId;
+
+ // Setting the text format for a cell will set the CellValueType to text
+ const type = getCellTypeByPattern(cell, value.pattern);
+ if (cell.v !== undefined) {
+ cell.t = type;
+ cell.v = getCellValue(type, cell);
+ }
}
});
});