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.

refactor(core,sheet): add exact style key metadata and reuse typed key aliases (#6731)

白熱4850a4d5d66d
diff --git a/packages/core/src/types/enum/theme-color-type.ts b/packages/core/src/types/enum/theme-color-type.ts
index 9fe141376a..e8ed7460fb 100644
--- a/packages/core/src/types/enum/theme-color-type.ts
+++ b/packages/core/src/types/enum/theme-color-type.ts
@@ -43,10 +43,9 @@ export enum ThemeColorType {
FOLLOWED_HYPERLINK,
}
-// TODO: get color list to color picker
-// TODO: 取色
-
/**
+ * Preset theme names.
+ *
* @deprecated
*/
export enum ThemeColors {
diff --git a/packages/core/src/types/interfaces/i-style-data.ts b/packages/core/src/types/interfaces/i-style-data.ts
index 75b5b8c530..ff02905a5d 100644
--- a/packages/core/src/types/interfaces/i-style-data.ts
+++ b/packages/core/src/types/interfaces/i-style-data.ts
@@ -27,6 +27,17 @@ import type {
} from '../enum/text-style';
import type { ThemeColorType } from '../enum/theme-color-type';
+type ExactKeys<T extends object, K extends readonly (keyof T)[]> =
+ Exclude<keyof T, K[number]> extends never
+ ? Exclude<K[number], keyof T> extends never
+ ? K
+ : never
+ : never;
+
+function defineExactKeys<T extends object>() {
+ return <const K extends readonly (keyof T)[]>(keys: ExactKeys<T, K>) => keys;
+}
+
/**
* Properties of text decoration
*/
@@ -49,15 +60,41 @@ export interface ITextDecoration {
t?: TextDecoration;
}
+/**
+ * Exact keys of {@link ITextDecoration}.
+ */
+export const TEXT_DECORATION_KEYS = defineExactKeys<ITextDecoration>()(['s', 'c', 'cl', 't'] as const);
+
+/**
+ * Key union of {@link ITextDecoration}.
+ */
+export type TextDecorationKey = (typeof TEXT_DECORATION_KEYS)[number];
+
/**
* RGB color or theme color
*/
export interface IColorStyle {
- // rgb?: Nullable<IColor | string>;
+ /**
+ * RGB color string, such as `#RRGGBB` or `rgb(r, g, b)`.
+ */
rgb?: Nullable<string>;
+
+ /**
+ * Theme color token.
+ */
th?: ThemeColorType;
}
+/**
+ * Exact keys of {@link IColorStyle}.
+ */
+export const COLOR_STYLE_KEYS = defineExactKeys<IColorStyle>()(['rgb', 'th'] as const);
+
+/**
+ * Key union of {@link IColorStyle}.
+ */
+export type ColorStyleKey = (typeof COLOR_STYLE_KEYS)[number];
+
/**
* Format of RBGA color
*/
@@ -76,6 +113,16 @@ export interface IBorderStyleData {
cl: IColorStyle;
}
+/**
+ * Exact keys of {@link IBorderStyleData}.
+ */
+export const BORDER_STYLE_KEYS = defineExactKeys<IBorderStyleData>()(['s', 'cl'] as const);
+
+/**
+ * Key union of {@link IBorderStyleData}.
+ */
+export type BorderStyleKey = (typeof BORDER_STYLE_KEYS)[number];
+
/**
* Style properties of top, bottom, left and right border
*
@@ -105,6 +152,16 @@ export interface IBorderData {
bc_tr?: Nullable<IBorderStyleData>;
}
+/**
+ * Exact keys of {@link IBorderData}.
+ */
+export const BORDER_KEYS = defineExactKeys<IBorderData>()(['t', 'r', 'b', 'l', 'tl_br', 'tl_bc', 'tl_mr', 'bl_tr', 'ml_tr', 'bc_tr'] as const);
+
+/**
+ * Key union of {@link IBorderData}.
+ */
+export type BorderKey = (typeof BORDER_KEYS)[number];
+
export interface ITextRotation {
/**
* angle
@@ -118,6 +175,16 @@ export interface ITextRotation {
v?: BooleanNumber;
}
+/**
+ * Exact keys of {@link ITextRotation}.
+ */
+export const TEXT_ROTATION_KEYS = defineExactKeys<ITextRotation>()(['a', 'v'] as const);
+
+/**
+ * Key union of {@link ITextRotation}.
+ */
+export type TextRotationKey = (typeof TEXT_ROTATION_KEYS)[number];
+
/**
* Top,right,bottom,left padding
*/
@@ -128,6 +195,16 @@ export interface IPaddingData {
l?: number;
}
+/**
+ * Exact keys of {@link IPaddingData}.
+ */
+export const PADDING_KEYS = defineExactKeys<IPaddingData>()(['t', 'r', 'b', 'l'] as const);
+
+/**
+ * Key union of {@link IPaddingData}.
+ */
+export type PaddingKey = (typeof PADDING_KEYS)[number];
+
/**
* Basics properties of cell style
*/
@@ -229,3 +306,33 @@ export interface IStyleData extends IStyleBase {
*/
pd?: Nullable<IPaddingData>;
}
+
+/**
+ * Exact keys of {@link IStyleData}.
+ */
+export const STYLE_KEYS = defineExactKeys<IStyleData>()([
+ 'ff',
+ 'fs',
+ 'it',
+ 'bl',
+ 'ul',
+ 'bbl',
+ 'st',
+ 'ol',
+ 'bg',
+ 'bd',
+ 'cl',
+ 'va',
+ 'n',
+ 'tr',
+ 'td',
+ 'ht',
+ 'vt',
+ 'tb',
+ 'pd',
+] as const);
+
+/**
+ * Key union of {@link IStyleData}.
+ */
+export type StyleKey = (typeof STYLE_KEYS)[number];
diff --git a/packages/sheets/src/basics/__tests__/cell-style.spec.ts b/packages/sheets/src/basics/__tests__/cell-style.spec.ts
new file mode 100644
index 0000000000..b24532786e
--- /dev/null
+++ b/packages/sheets/src/basics/__tests__/cell-style.spec.ts
@@ -0,0 +1,82 @@
+/**
+ * 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 type { ICellData } from '@univerjs/core';
+import { Styles } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { handleStyle, transformStyle } from '../cell-style';
+
+describe('Test cell style sanitization', () => {
+ it('ignores unexpected keys when merging cell borders', () => {
+ const styles = new Styles();
+ const oldVal: ICellData = {
+ s: {
+ bd: {
+ l: {
+ s: 0 as never,
+ cl: { rgb: '#000000' },
+ },
+ },
+ },
+ };
+
+ const newVal: ICellData = {
+ s: JSON.parse(`{
+ "bd": {
+ "__proto__": { "polluted": "yes" },
+ "evil": { "s": 2, "cl": { "rgb": "#ff00ff" } },
+ "t": { "s": 1, "cl": { "rgb": "#ff0000" }, "extra": true }
+ },
+ "unexpected": { "enabled": true },
+ "__proto__": { "polluted": "yes" }
+ }`) as ICellData['s'],
+ };
+
+ handleStyle(styles, oldVal, newVal);
+
+ expect(styles.getStyleByCell(oldVal)).toEqual({
+ bd: {
+ l: {
+ s: 0,
+ cl: { rgb: '#000000' },
+ },
+ t: {
+ s: 1,
+ cl: { rgb: '#ff0000' },
+ },
+ },
+ });
+ expect((styles.getStyleByCell(oldVal)?.bd as Record<string, unknown>).evil).toBeUndefined();
+ expect((styles.getStyleByCell(oldVal) as Record<string, unknown>).unexpected).toBeUndefined();
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+
+ it('only records allowed border keys in undo snapshots', () => {
+ const backupStyle = transformStyle(null, JSON.parse(`{
+ "bd": {
+ "t": { "s": 1, "cl": { "rgb": "#00ff00" }, "extra": true },
+ "evil": { "s": 3, "cl": { "rgb": "#ff00ff" } }
+ },
+ "unexpected": { "enabled": true }
+ }`));
+
+ expect(backupStyle).toEqual({
+ bd: {
+ t: null,
+ },
+ });
+ });
+});
diff --git a/packages/sheets/src/basics/cell-style.ts b/packages/sheets/src/basics/cell-style.ts
index f9d233d18f..77731a6bff 100644
--- a/packages/sheets/src/basics/cell-style.ts
+++ b/packages/sheets/src/basics/cell-style.ts
@@ -14,8 +14,239 @@
* 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';
+import type {
+ BorderKey,
+ BorderStyleKey,
+ ColorStyleKey,
+ IBorderData,
+ IBorderStyleData,
+ ICellData,
+ IColorStyle,
+ IDocumentData,
+ IPaddingData,
+ IParagraph,
+ IStyleData,
+ ITextDecoration,
+ ITextRotation,
+ ITextRun,
+ ITextStyle,
+ Nullable,
+ PaddingKey,
+ StyleKey,
+ Styles,
+ TextDecorationKey,
+ TextRotationKey,
+} from '@univerjs/core';
+import {
+ BORDER_KEYS,
+ BORDER_STYLE_KEYS,
+ COLOR_STYLE_KEYS,
+ normalizeTextRuns,
+ PADDING_KEYS,
+ STYLE_KEYS,
+ TEXT_DECORATION_KEYS,
+ TEXT_ROTATION_KEYS,
+ Tools,
+} from '@univerjs/core';
+
+type UnknownRecord = Record<string, unknown>;
+type BorderRecord = Partial<Record<BorderKey, Nullable<IBorderStyleData>>>;
+
+function isPlainRecord(value: unknown): value is UnknownRecord {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function forEachPresentKey<K extends string>(
+ value: UnknownRecord,
+ keys: readonly K[],
+ iteratee: (key: K, fieldValue: unknown) => void
+) {
+ for (const key of keys) {
+ if (!Object.prototype.hasOwnProperty.call(value, key)) {
+ continue;
+ }
+
+ iteratee(key, value[key]);
+ }
+}
+
+function sanitizeFixedShapeObject<T extends object, K extends string>(
+ value: unknown,
+ directKeys: readonly K[],
+ nestedSanitizers?: Record<string, (value: unknown) => unknown>
+): Nullable<T> | undefined {
+ if (value == null) {
+ return value as null | undefined;
+ }
+
+ if (!isPlainRecord(value)) {
+ return undefined;
+ }
+
+ const sanitized: UnknownRecord = {};
+ let hasFields = false;
+
+ forEachPresentKey(value, directKeys, (key, fieldValue) => {
+ sanitized[key] = fieldValue;
+ hasFields = true;
+ });
+
+ if (nestedSanitizers) {
+ for (const key in nestedSanitizers) {
+ const sanitize = nestedSanitizers[key];
+
+ if (!sanitize || !Object.prototype.hasOwnProperty.call(value, key)) {
+ continue;
+ }
+
+ const sanitizedValue = sanitize(value[key]);
+
+ if (sanitizedValue !== undefined) {
+ sanitized[key] = sanitizedValue;
+ hasFields = true;
+ }
+ }
+ }
+
+ return hasFields ? (sanitized as T) : undefined;
+}
+
+function sanitizeMappedObject<T extends object, K extends string>(
+ value: unknown,
+ keys: readonly K[],
+ sanitize: (value: unknown) => unknown
+): Nullable<T> | undefined {
+ if (value == null) {
+ return value as null | undefined;
+ }
+
+ if (!isPlainRecord(value)) {
+ return undefined;
+ }
+
+ const sanitized: UnknownRecord = {};
+ let hasFields = false;
+
+ forEachPresentKey(value, keys, (key, fieldValue) => {
+ const sanitizedValue = sanitize(fieldValue);
+
+ if (sanitizedValue !== undefined) {
+ sanitized[key] = sanitizedValue;
+ hasFields = true;
+ }
+ });
+
+ return hasFields ? (sanitized as T) : undefined;
+}
+
+function shouldSkipRichTextStyleKey(key: StyleKey): boolean {
+ switch (key) {
+ case 'bd':
+ case 'tr':
+ case 'td':
+ case 'ht':
+ case 'vt':
+ case 'tb':
+ case 'pd':
+ case 'bg':
+ return true;
+ default:
+ return false;
+ }
+}
+
+function isSerializablePrimitive(value: unknown): value is string | number | boolean | null | undefined {
+ return value == null || ['string', 'number', 'boolean'].includes(typeof value);
+}
+
+function sanitizeColorStyle(value: unknown): Nullable<IColorStyle> | undefined {
+ return sanitizeFixedShapeObject<IColorStyle, ColorStyleKey>(value, COLOR_STYLE_KEYS);
+}
+
+function sanitizeTextDecoration(value: unknown): Nullable<ITextDecoration> | undefined {
+ return sanitizeFixedShapeObject<ITextDecoration, TextDecorationKey>(value, TEXT_DECORATION_KEYS, {
+ cl: sanitizeColorStyle,
+ });
+}
+
+function sanitizeBorderStyleData(value: unknown): Nullable<IBorderStyleData> | undefined {
+ return sanitizeFixedShapeObject<IBorderStyleData, BorderStyleKey>(value, BORDER_STYLE_KEYS, {
+ cl: sanitizeColorStyle,
+ });
+}
+
+function sanitizeBorderData(value: unknown): Nullable<IBorderData> | undefined {
+ return sanitizeMappedObject<IBorderData, BorderKey>(value, BORDER_KEYS, sanitizeBorderStyleData);
+}
+
+function sanitizeTextRotation(value: unknown): Nullable<ITextRotation> | undefined {
+ return sanitizeFixedShapeObject<ITextRotation, TextRotationKey>(value, TEXT_ROTATION_KEYS);
+}
+
+function sanitizePaddingData(value: unknown): Nullable<IPaddingData> | undefined {
+ return sanitizeFixedShapeObject<IPaddingData, PaddingKey>(value, PADDING_KEYS);
+}
+
+function sanitizeNumberFormat(value: unknown): Nullable<{ pattern: string }> | undefined {
+ if (value == null) {
+ return value as null | undefined;
+ }
+
+ if (!isPlainRecord(value) || !Object.prototype.hasOwnProperty.call(value, 'pattern') || typeof value.pattern !== 'string') {
+ return undefined;
+ }
+
+ return { pattern: value.pattern };
+}
+
+function sanitizeStyleValue(key: StyleKey, value: unknown): unknown {
+ switch (key) {
+ case 'ul':
+ case 'bbl':
+ case 'st':
+ case 'ol':
+ return sanitizeTextDecoration(value);
+ case 'bg':
+ case 'cl':
+ return sanitizeColorStyle(value);
+ case 'bd':
+ return sanitizeBorderData(value);
+ case 'tr':
+ return sanitizeTextRotation(value);
+ case 'pd':
+ return sanitizePaddingData(value);
+ case 'n':
+ return sanitizeNumberFormat(value);
+ default:
+ return isSerializablePrimitive(value) ? value : undefined;
+ }
+}
+
+function mergeBorderData(
+ currentBorders: Nullable<IBorderData>,
+ incomingBorders: Nullable<IBorderData>
+): Nullable<IBorderData> {
+ if (incomingBorders === null) {
+ return null;
+ }
+
+ if (incomingBorders === undefined) {
+ return currentBorders;
+ }
+
+ const borderRecord = incomingBorders as BorderRecord;
+ const mergedBorders: BorderRecord = Tools.isObject(currentBorders) ? { ...(currentBorders as BorderRecord) } : {};
+
+ forEachPresentKey(borderRecord as UnknownRecord, BORDER_KEYS, (key, fieldValue) => {
+ const borderStyle = sanitizeBorderStyleData(fieldValue);
+
+ if (borderStyle !== undefined) {
+ mergedBorders[key] = borderStyle;
+ }
+ });
+
+ return mergedBorders as IBorderData;
+}
/**
*
@@ -79,19 +310,30 @@ export function transformStyle(oldStyle: Nullable<IStyleData>, newStyle: Nullabl
if (!newStyle || !Object.keys(newStyle).length) {
return oldStyle;
}
- const backupStyle: Record<string, any> = Tools.deepClone(oldStyle ?? {});
+ const backupStyle = (Tools.deepClone(oldStyle ?? {}) || {}) as UnknownRecord;
+ const styleRecord = newStyle as UnknownRecord;
- for (const k in newStyle) {
- if (k === 'bd') {
- backupStyle[k] = transformBorders(backupStyle[k] || {}, newStyle[k]);
+ for (const key of STYLE_KEYS) {
+ if (!Object.prototype.hasOwnProperty.call(styleRecord, key)) {
+ continue;
+ }
+
+ const sanitizedValue = sanitizeStyleValue(key, styleRecord[key]);
+
+ if (sanitizedValue === undefined) {
+ continue;
+ }
+
+ if (key === 'bd') {
+ backupStyle[key] = transformBorders((backupStyle[key] as IBorderData) || {}, sanitizedValue as Nullable<IBorderData>);
}
// 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;
+ else if (!(key in backupStyle)) {
+ backupStyle[key] = null;
}
}
- return backupStyle;
+ return backupStyle as Nullable<IStyleData>;
}
/**
@@ -106,11 +348,17 @@ function transformBorders(oldBorders: IBorderData, newBorders: Nullable<IBorderD
return oldBorders;
}
- for (const k in newBorders) {
+ const oldBorderRecord = oldBorders as BorderRecord;
+
+ for (const key of BORDER_KEYS) {
+ if (!Object.prototype.hasOwnProperty.call(newBorders as UnknownRecord, key)) {
+ continue;
+ }
+
// 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;
+ if (!(key in oldBorders)) {
+ oldBorderRecord[key] = null;
}
}
@@ -133,36 +381,51 @@ function mergeStyle(
// don't operate
if (newStyle === undefined) return oldStyle;
- const backupStyle: Record<string, any> = Tools.deepClone(oldStyle) || {};
+ const backupStyle = (Tools.deepClone(oldStyle) || {}) as UnknownRecord;
+ const styleRecord = newStyle as UnknownRecord;
+
+ for (const key of STYLE_KEYS) {
+ if (!Object.prototype.hasOwnProperty.call(styleRecord, key)) {
+ continue;
+ }
- for (const k in newStyle) {
// Do not copy cell background color to rich text background color.
- if (isRichText && ['bd', 'tr', 'td', 'ht', 'vt', 'tb', 'pd', 'bg'].includes(k)) {
+ if (isRichText && shouldSkipRichTextStyleKey(key)) {
continue;
}
+
+ const sanitizedValue = sanitizeStyleValue(key, styleRecord[key]);
+
+ if (sanitizedValue === undefined) {
+ 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]);
+ if (key === 'bd') {
+ backupStyle[key] = mergeBorderData(backupStyle[key] as Nullable<IBorderData>, sanitizedValue as Nullable<IBorderData>);
} else {
- backupStyle[k] = (newStyle as IKeyValue)[k];
+ backupStyle[key] = sanitizedValue;
}
}
if ('cl' in backupStyle) {
- if ('ul' in backupStyle && backupStyle.ul) {
- backupStyle.ul.cl = backupStyle.cl;
+ const backupStyleData = backupStyle as IStyleData;
+ const color = backupStyleData.cl;
+
+ if ('ul' in backupStyleData && backupStyleData.ul) {
+ backupStyleData.ul.cl = color as IColorStyle;
}
- if ('ol' in backupStyle && backupStyle.ol) {
- backupStyle.ol.cl = backupStyle.cl;
+ if ('ol' in backupStyleData && backupStyleData.ol) {
+ backupStyleData.ol.cl = color as IColorStyle;
}
- if ('st' in backupStyle && backupStyle.st) {
- backupStyle.st.cl = backupStyle.cl;
+ if ('st' in backupStyleData && backupStyleData.st) {
+ backupStyleData.st.cl = color as IColorStyle;
}
}
- return backupStyle;
+ return backupStyle as Nullable<IStyleData>;
}
/**