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.

feat(core): extend rich text facade builder (#7232)

Univer2e54bd0074e1
diff --git a/packages/core/src/docs/data-model/__tests__/rich-text-builder.test.ts b/packages/core/src/docs/data-model/__tests__/rich-text-builder.test.ts
index 7df8f56592..b31867984d 100644
--- a/packages/core/src/docs/data-model/__tests__/rich-text-builder.test.ts
+++ b/packages/core/src/docs/data-model/__tests__/rich-text-builder.test.ts
@@ -17,7 +17,8 @@
import type { IBullet } from '../../../types/interfaces';
import { describe, expect, it } from 'vitest';
import { BaselineOffset, BooleanNumber, HorizontalAlign, TextDecoration, TextDirection } from '../../../types/enum';
-import { CustomRangeType } from '../../../types/interfaces';
+import { CustomRangeType, SpacingRule } from '../../../types/interfaces';
+import { PresetListType } from '../preset-list-type';
import { ParagraphStyleBuilder, RichTextBuilder, RichTextValue, TextDecorationBuilder, TextStyleBuilder } from '../rich-text-builder';
describe('TextStyleBuilder', () => {
@@ -353,6 +354,78 @@ describe('RichTextBuilder', () => {
expect(data.textRuns![0].st).toBe(0);
expect(data.textRuns![0].ed).toBe(5);
});
+
+ it('should build agent-friendly styled spans', () => {
+ const builder = RichTextBuilder.create()
+ .text('Status: ')
+ .span('Important', { bold: true, italic: true, color: '#d92d20' })
+ .text(' ')
+ .bold('High')
+ .text(' ')
+ .italic('now');
+
+ const data = builder.getData().body!;
+
+ expect(data.dataStream).toBe('Status: Important High now\r\n');
+ expect(data.textRuns).toEqual([
+ {
+ st: 8,
+ ed: 17,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ it: BooleanNumber.TRUE,
+ cl: { rgb: '#d92d20' },
+ },
+ },
+ {
+ st: 18,
+ ed: 22,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ {
+ st: 23,
+ ed: 26,
+ ts: {
+ it: BooleanNumber.TRUE,
+ },
+ },
+ ]);
+ });
+
+ it('should build inline code as a text style', () => {
+ const builder = RichTextBuilder.create()
+ .text('Run ')
+ .code('pnpm test')
+ .text(' before submitting.');
+
+ const data = builder.getData().body!;
+
+ expect(data.dataStream).toBe('Run pnpm test before submitting.\r\n');
+ expect(data.textRuns).toHaveLength(1);
+ const codeRun = data.textRuns![0]!;
+ expect(codeRun).toMatchObject({
+ st: 4,
+ ed: 13,
+ ts: {
+ bg: { rgb: '#f3f4f6' },
+ },
+ });
+ expect(codeRun.ts!.ff).toContain('monospace');
+ });
+
+ it('should ignore empty styled spans', () => {
+ const builder = RichTextBuilder.create()
+ .text('Hello')
+ .span('', { bold: true, italic: true })
+ .text(' World');
+
+ const data = builder.getData().body!;
+
+ expect(data.dataStream).toBe('Hello World\r\n');
+ expect(data.textRuns).toHaveLength(0);
+ });
});
describe('rich text insertion', () => {
@@ -502,6 +575,88 @@ describe('RichTextBuilder', () => {
});
describe('paragraph management', () => {
+ it('should start a paragraph chain without a leading blank paragraph', () => {
+ const builder = RichTextBuilder.create()
+ .paragraph()
+ .text('Title')
+ .paragraph()
+ .span('Body', { bold: true, italic: true });
+
+ const data = builder.getData().body!;
+
+ expect(data.dataStream).toBe('Title\rBody\r\n');
+ expect(data.paragraphs).toHaveLength(2);
+ expect(data.textRuns).toEqual([
+ {
+ st: 6,
+ ed: 10,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ it: BooleanNumber.TRUE,
+ },
+ },
+ ]);
+ });
+
+ it('should apply agent-friendly options to the following paragraph', () => {
+ const builder = RichTextBuilder.create()
+ .paragraph({
+ align: HorizontalAlign.LEFT,
+ lineHeight: 1.4,
+ firstLineIndent: 16,
+ indentStart: 8,
+ spaceAfter: 6,
+ })
+ .text('First')
+ .paragraph({
+ align: HorizontalAlign.RIGHT,
+ lineHeight: 24,
+ lineHeightRule: SpacingRule.EXACT,
+ hangingIndent: { v: 10 },
+ spaceBefore: 4,
+ keepNext: true,
+ })
+ .text('Second');
+
+ const data = builder.getData().body!;
+
+ expect(data.dataStream).toBe('First\rSecond\r\n');
+ expect(data.paragraphs?.[0]?.paragraphStyle).toMatchObject({
+ horizontalAlign: HorizontalAlign.LEFT,
+ lineSpacing: 1.4,
+ indentFirstLine: { v: 16 },
+ indentStart: { v: 8 },
+ spaceBelow: { v: 6 },
+ });
+ expect(data.paragraphs?.[1]?.paragraphStyle).toMatchObject({
+ horizontalAlign: HorizontalAlign.RIGHT,
+ lineSpacing: 24,
+ spacingRule: SpacingRule.EXACT,
+ hanging: { v: 10 },
+ spaceAbove: { v: 4 },
+ keepNext: BooleanNumber.TRUE,
+ });
+ });
+
+ it('should build stable nested list items and end the list on a normal paragraph', () => {
+ const builder = RichTextBuilder.create()
+ .listItem('Plan', { listId: 'agent.tasks' })
+ .listItem('Implement', { listId: 'agent.tasks', level: 1 })
+ .listItem('Verify', { type: PresetListType.ORDER_LIST, listId: 'agent.steps' })
+ .paragraph()
+ .text('Summary');
+
+ const data = builder.getData().body!;
+
+ expect(data.dataStream).toBe('Plan\rImplement\rVerify\rSummary\r\n');
+ expect(data.paragraphs?.map((paragraph) => paragraph.bullet)).toEqual([
+ { listId: 'agent.tasks', listType: PresetListType.BULLET_LIST, nestingLevel: 0 },
+ { listId: 'agent.tasks', listType: PresetListType.BULLET_LIST, nestingLevel: 1 },
+ { listId: 'agent.steps', listType: PresetListType.ORDER_LIST, nestingLevel: 0 },
+ undefined,
+ ]);
+ });
+
it('should insert paragraph at the end', () => {
const style = ParagraphStyleBuilder.create()
.setHorizontalAlign(HorizontalAlign.CENTER);
diff --git a/packages/core/src/docs/data-model/preset-list-type.ts b/packages/core/src/docs/data-model/preset-list-type.ts
index 18db3cdcf4..2f9797bf12 100644
--- a/packages/core/src/docs/data-model/preset-list-type.ts
+++ b/packages/core/src/docs/data-model/preset-list-type.ts
@@ -31,45 +31,58 @@ export enum QuickListType {
}
export enum PresetListType {
+ /** Standard filled-circle bullet list. */
BULLET_LIST = 'BULLET_LIST',
+ /** Decorative diamond and arrow bullet list. */
BULLET_LIST_1 = 'BULLET_LIST_1',
+ /** Checkmark-led bullet list for completed-item style content. */
BULLET_LIST_2 = 'BULLET_LIST_2',
+ /** Square and diamond bullet list. */
BULLET_LIST_3 = 'BULLET_LIST_3',
+ /** Star-like decorative bullet list. */
BULLET_LIST_4 = 'BULLET_LIST_4',
+ /** Arrow-led bullet list. */
BULLET_LIST_5 = 'BULLET_LIST_5',
/**
- * 1 a i
+ * Hierarchical ordered list using `1`, `a`, and `i` markers.
*/
ORDER_LIST = 'ORDER_LIST',
/**
- * 1) a) i)
+ * Hierarchical ordered list using `1)`, `a)`, and `i)` markers.
*/
ORDER_LIST_1 = 'ORDER_LIST_1',
/**
- * 1. 1.1. 1.1.1.
+ * Outline list using compound markers such as `1.`, `1.1.`, and `1.1.1.`.
*/
ORDER_LIST_2 = 'ORDER_LIST_2',
/**
- * A a i
+ * Hierarchical ordered list using `A`, `a`, and `i` markers.
*/
ORDER_LIST_3 = 'ORDER_LIST_3',
/**
- * A 1 i
+ * Hierarchical ordered list using `A`, `1`, and `i` markers.
*/
ORDER_LIST_4 = 'ORDER_LIST_4',
/**
- * 01 a i
+ * Zero-padded ordered list using `01`, `a`, and `i` markers.
*/
ORDER_LIST_5 = 'ORDER_LIST_5',
+ /** Quick ordered list using closing-parenthesis markers. */
ORDER_LIST_QUICK_2 = 'ORDER_LIST_QUICK_2',
+ /** Quick ordered list using lowercase letter and period markers. */
ORDER_LIST_QUICK_3 = 'ORDER_LIST_QUICK_3',
+ /** Quick ordered list using lowercase Roman numeral markers. */
ORDER_LIST_QUICK_4 = 'ORDER_LIST_QUICK_4',
+ /** Quick ordered list using uppercase letter markers. */
ORDER_LIST_QUICK_5 = 'ORDER_LIST_QUICK_5',
+ /** Quick ordered list using uppercase Roman numeral markers. */
ORDER_LIST_QUICK_6 = 'ORDER_LIST_QUICK_6',
+ /** Unchecked task-list item. */
CHECK_LIST = 'CHECK_LIST',
+ /** Checked task-list item. */
CHECK_LIST_CHECKED = 'CHECK_LIST_CHECKED',
}
diff --git a/packages/core/src/docs/data-model/rich-text-builder.ts b/packages/core/src/docs/data-model/rich-text-builder.ts
index 5f539b9173..cead9d87f5 100644
--- a/packages/core/src/docs/data-model/rich-text-builder.ts
+++ b/packages/core/src/docs/data-model/rich-text-builder.ts
@@ -37,6 +37,7 @@ import { BooleanNumber } from '../../types/enum';
import { CustomRangeType } from '../../types/interfaces';
import { createParagraphId } from '../paragraph-id';
import { DocumentDataModel } from './document-data-model';
+import { PresetListType } from './preset-list-type';
import { BuildTextUtils } from './text-x/build-utils';
import { TextX } from './text-x/text-x';
import { getBodySlice } from './text-x/utils';
@@ -96,6 +97,201 @@ export function normalizeData(data: IDocumentData) {
return data;
}
+/**
+ * Agent-friendly text style aliases accepted by `RichTextBuilder.span()`.
+ *
+ * The readable aliases can be combined in one object and apply only to the appended span. Native `ITextStyle` fields
+ * remain available for advanced document integrations.
+ *
+ * @example
+ * ```ts
+ * const text = univerAPI.newRichText()
+ * .text('Status: ')
+ * .span('Blocked', {
+ * bold: true,
+ * italic: true,
+ * color: '#dc2626',
+ * background: '#fee2e2',
+ * });
+ * ```
+ */
+export interface IRichTextSpanStyle extends ITextStyle {
+ /**
+ * Agent-friendly alias for `bl`.
+ */
+ bold?: boolean;
+ /**
+ * Agent-friendly alias for `it`.
+ */
+ italic?: boolean;
+ /**
+ * Agent-friendly alias for `ff`.
+ */
+ fontFamily?: string;
+ /**
+ * Agent-friendly alias for `fs`.
+ */
+ fontSize?: number;
+ /**
+ * Agent-friendly alias for `cl`. A string is treated as an RGB color.
+ */
+ color?: string | IColorStyle | null;
+ /**
+ * Agent-friendly alias for `bg`. A string is treated as an RGB color.
+ */
+ background?: string | IColorStyle | null;
+}
+
+/**
+ * Agent-friendly paragraph options accepted by `RichTextBuilder.paragraph()`.
+ *
+ * Numeric lengths use document points. Pass an `INumberUnit` when another supported unit is required. `lineHeight`
+ * behaves as a multiplier with `SpacingRule.AUTO`, and as an absolute document size with `AT_LEAST` or `EXACT`.
+ *
+ * @example
+ * ```ts
+ * const text = univerAPI.newRichText()
+ * .paragraph({
+ * align: univerAPI.Enum.HorizontalAlign.LEFT,
+ * lineHeight: 1.4,
+ * lineHeightRule: univerAPI.Enum.SpacingRule.AUTO,
+ * firstLineIndent: 12,
+ * spaceAfter: 6,
+ * })
+ * .text('Agent-friendly paragraph');
+ * ```
+ */
+export interface IRichTextParagraphStyle {
+ /** Horizontal paragraph alignment. Use `univerAPI.Enum.HorizontalAlign`. */
+ align?: HorizontalAlign;
+ /** Line-height multiplier or absolute size, depending on `lineHeightRule`. */
+ lineHeight?: number;
+ /** Line-height interpretation. Defaults to `SpacingRule.AUTO`. */
+ lineHeightRule?: SpacingRule;
+ /** First-line indent. A number is interpreted as document points. */
+ firstLineIndent?: number | INumberUnit;
+ /** Hanging indent. A number is interpreted as document points. */
+ hangingIndent?: number | INumberUnit;
+ /** Leading-side indent. A number is interpreted as document points. */
+ indentStart?: number | INumberUnit;
+ /** Trailing-side indent. A number is interpreted as document points. */
+ indentEnd?: number | INumberUnit;
+ /** Space before the paragraph. A number is interpreted as document points. */
+ spaceBefore?: number | INumberUnit;
+ /** Space after the paragraph. A number is interpreted as document points. */
+ spaceAfter?: number | INumberUnit;
+ /** Text direction. Use `univerAPI.Enum.TextDirection`. */
+ direction?: TextDirection;
+ /** Whether lines may wrap at character boundaries. */
+ wordWrap?: boolean;
+ /** Keeps all paragraph lines together when pagination applies. */
+ keepLines?: boolean;
+ /** Keeps this paragraph with the following paragraph when pagination applies. */
+ keepNext?: boolean;
+}
+
+/**
+ * Agent-friendly options for one paragraph list item.
+ *
+ * @example
+ * ```ts
+ * const text = univerAPI.newRichText()
+ * .listItem('Plan', {
+ * type: univerAPI.Enum.PresetListType.ORDER_LIST,
+ * listId: 'agent.release-steps',
+ * })
+ * .listItem('Build', {
+ * type: univerAPI.Enum.PresetListType.ORDER_LIST,
+ * listId: 'agent.release-steps',
+ * level: 1,
+ * });
+ * ```
+ */
+export interface IRichTextListItemOptions {
+ /** Preset ordered, unordered, or checklist style. Defaults to `PresetListType.BULLET_LIST`. */
+ type?: PresetListType;
+ /** Stable list identity. Consecutive compatible items reuse the previous id when omitted. */
+ listId?: string;
+ /** Zero-based nesting level. Defaults to `0`. */
+ level?: number;
+ /** Optional paragraph layout for this item. */
+ paragraphStyle?: ParagraphStyleBuilder | IRichTextParagraphStyle;
+}
+
+function normalizeColorStyle(color: string | IColorStyle | null | undefined): IColorStyle | null | undefined {
+ return typeof color === 'string' ? { rgb: color } : color;
+}
+
+function normalizeRichTextSpanStyle(style: IRichTextSpanStyle): ITextStyle {
+ const {
+ bold,
+ italic,
+ fontFamily,
+ fontSize,
+ color,
+ background,
+ ...rawStyle
+ } = style;
+ const normalized: ITextStyle = { ...rawStyle };
+
+ if (bold !== undefined) {
+ normalized.bl = bold ? BooleanNumber.TRUE : BooleanNumber.FALSE;
+ }
+ if (italic !== undefined) {
+ normalized.it = italic ? BooleanNumber.TRUE : BooleanNumber.FALSE;
+ }
+ if (fontFamily !== undefined) {
+ normalized.ff = fontFamily;
+ }
+ if (fontSize !== undefined) {
+ normalized.fs = fontSize;
+ }
+ if (color !== undefined) {
+ normalized.cl = normalizeColorStyle(color);
+ }
+ if (background !== undefined) {
+ normalized.bg = normalizeColorStyle(background);
+ }
+
+ return normalized;
+}
+
+function normalizeRichTextLength(value: number | INumberUnit | undefined): INumberUnit | undefined {
+ return typeof value === 'number' ? { v: value } : value;
+}
+
+function normalizeRichTextParagraphStyle(
+ style: ParagraphStyleBuilder | IRichTextParagraphStyle | undefined
+): IParagraphStyle | undefined {
+ if (!style) {
+ return undefined;
+ }
+ if (style instanceof ParagraphStyleBuilder) {
+ return style.build();
+ }
+
+ return {
+ horizontalAlign: style.align,
+ lineSpacing: style.lineHeight,
+ spacingRule: style.lineHeightRule,
+ indentFirstLine: normalizeRichTextLength(style.firstLineIndent),
+ hanging: normalizeRichTextLength(style.hangingIndent),
+ indentStart: normalizeRichTextLength(style.indentStart),
+ indentEnd: normalizeRichTextLength(style.indentEnd),
+ spaceAbove: normalizeRichTextLength(style.spaceBefore),
+ spaceBelow: normalizeRichTextLength(style.spaceAfter),
+ direction: style.direction,
+ wordWrap: style.wordWrap === undefined ? undefined : style.wordWrap ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ keepLines: style.keepLines === undefined ? undefined : style.keepLines ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ keepNext: style.keepNext === undefined ? undefined : style.keepNext ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ };
+}
+
+function hasRichTextContent(data: IDocumentData): boolean {
+ const dataStream = data.body?.dataStream ?? '';
+ return dataStream.replace(/\r|\n/g, '').length > 0;
+}
+
/**
* Represents a read-only font style value object.
* This class provides access to font style properties without modification capabilities.
@@ -1705,6 +1901,22 @@ export class RichTextValue {
* Represents a rich text builder
*/
export class RichTextBuilder extends RichTextValue {
+ /**
+ * Allows optional feature packages to add semantic builder methods.
+ * @internal
+ */
+ static extend(source: typeof RichTextBuilder): void {
+ Object.getOwnPropertyNames(source.prototype).forEach((name) => {
+ if (name === 'constructor') {
+ return;
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(source.prototype, name);
+ if (descriptor) {
+ Object.defineProperty(this.prototype, name, descriptor);
+ }
+ });
+ }
+
public static newEmptyData(): IDocumentData {
return normalizeData({
id: 'd',
@@ -1739,6 +1951,223 @@ export class RichTextBuilder extends RichTextValue {
this._doc = new DocumentDataModel(data);
}
+ /**
+ * Appends plain text to the rich text.
+ *
+ * This is an agent-friendly alias of `insertText(text)`. Use it when building rich text from left to right for
+ * shapes, comments, table cells, and document fragments.
+ *
+ * @param text Text to append.
+ * @returns The current builder for chaining.
+ * @example
+ * ```ts
+ * const richText = univerAPI.newRichText()
+ * .text('Priority: ')
+ * .bold('High')
+ * .text(' ')
+ * .code('P0');
+ * ```
+ */
+ text(text: string): RichTextBuilder {
+ return this.insertText(text);
+ }
+
+ /**
+ * Appends one text span with explicit style.
+ *
+ * Prefer this method when combining multiple styles, because the style object is local to the inserted text and does
+ * not leak into following calls.
+ *
+ * @param text Text to append.
+ * @param style Text style for this span. Agent-friendly aliases such as `bold`, `italic`, `fontFamily`, `fontSize`,
+ * `color`, and `background` are supported alongside native document text style fields.
+ * @returns The current builder for chaining.
+ * @example
+ * ```ts
+ * const richText = univerAPI.newRichText()
+ * .text('Status: ')
+ * .span('Important', { bold: true, italic: true, color: '#d92d20' });
+ * ```
+ */
+ span(text: string, style: IRichTextSpanStyle): RichTextBuilder {
+ if (!text) {
+ return this;
+ }
+
+ return this.insertRichText(RichTextValue.create({
+ id: 'd',
+ documentStyle: {},
+ body: {
+ dataStream: text,
+ textRuns: [{
+ st: 0,
+ ed: text.length,
+ ts: normalizeRichTextSpanStyle(style),
+ }],
+ },
+ }));
+ }
+
+ /**
+ * Appends bold text.
+ *
+ * @param text Text to append.
+ * @returns The current builder for chaining.
+ * @example
+ * ```ts
+ * const richText = univerAPI.newRichText().text('This is ').bold('important');
+ * ```
+ */
+ bold(text: string): RichTextBuilder {
+ return this.span(text, { bold: true });
+ }
+
+ /**
+ * Appends italic text.
+ *
+ * @param text Text to append.
+ * @returns The current builder for chaining.
+ * @example
+ * ```ts
+ * const richText = univerAPI.newRichText().text('Use ').italic('judgment');
+ * ```
+ */
+ italic(text: string): RichTextBuilder {
+ return this.span(text, { italic: true });
+ }
+
+ /**
+ * Appends inline code-style text.
+ *
+ * This is intentionally an inline text style, not a block range. Use `paragraph().code('...')` when the code should
+ * occupy its own line.
+ *
+ * @param text Text to append as inline code.
+ * @returns The current builder for chaining.
+ * @example
+ * ```ts
+ * const richText = univerAPI.newRichText()
+ * .text('Run ')
+ * .code('pnpm test')
+ * .text(' before submitting.');
+ * ```
+ */
+ code(text: string): RichTextBuilder {
+ return this.span(text, {
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
+ background: '#f3f4f6',
+ });
+ }
+
+ /**
+ * Appends one ordered, unordered, or checklist paragraph.
+ *
+ * Consecutive items with the same `type` automatically share a generated list id. Supply a semantic `listId` when
+ * an agent needs stable list identity across regeneration.
+ *
+ * @param text Plain item text.
+ * @param options List type, stable identity, nesting, and optional paragraph layout.
+ * @returns The current builder for chaining.
+ * @example
+ * ```ts
+ * const richText = univerAPI.newRichText()
+ * .listItem('Analyze requirements', {
+ * type: univerAPI.Enum.PresetListType.BULLET_LIST,
+ * listId: 'agent.tasks',
+ * })
+ * .listItem('Implement API', {
+ * type: univerAPI.Enum.PresetListType.BULLET_LIST,
+ * listId: 'agent.tasks',
+ * level: 1,
+ * });
+ * ```
+ */
+ listItem(text: string, options: IRichTextListItemOptions = {}): RichTextBuilder {
+ const listType = options.type ?? PresetListType.BULLET_LIST;
+ const currentParagraph = this._data.body?.paragraphs?.at(-1);
+ const currentBullet = currentParagraph?.bullet;
+ const listId = options.listId?.trim() ||
+ (currentBullet?.listType === listType ? currentBullet.listId : generateRandomId());
+
+ if (hasRichTextContent(this._data)) {
+ this.paragraph(options.paragraphStyle);
+ } else if (options.paragraphStyle) {
+ this.paragraph(options.paragraphStyle);
+ }
+
+ const targetParagraph = this._data.body?.paragraphs?.at(-1);
+ if (targetParagraph) {
+ targetParagraph.bullet = {
+ listId,
+ listType,
+ nestingLevel: Math.max(0, Math.trunc(options.level ?? 0)),
+ };
+ }
+
+ return this.text(text);
+ }
+
+ /**
+ * Starts a new paragraph before the next appended content.
+ *
+ * Calling `paragraph()` on an empty builder is a no-op, so agents can naturally start chains with
+ * `newRichText().paragraph().text('Title')` without creating a leading blank paragraph.
+ *
+ * @param paragraphStyle Optional agent-friendly paragraph options or an advanced paragraph style builder.
+ * @returns The current builder for chaining.
+ * @example
+ * ```ts
+ * const richText = univerAPI.newRichText()
+ * .paragraph({ lineHeight: 1.4, firstLineIndent: 16, spaceAfter: 8 })
+ * .text('First paragraph')
+ * .paragraph({ align: univerAPI.Enum.HorizontalAlign.CENTER })
+ * .span('Second paragraph', { bold: true, italic: true });
+ * ```
+ */
+ paragraph(paragraphStyle?: ParagraphStyleBuilder | IRichTextParagraphStyle): RichTextBuilder {
+ const nextParagraphStyle = normalizeRichTextParagraphStyle(paragraphStyle);
+ if (!hasRichTextContent(this._data)) {
+ if (nextParagraphStyle) {
+ const firstParagraph = this._data.body?.paragraphs?.[0];
+ if (firstParagraph) {
+ firstParagraph.paragraphStyle = nextParagraphStyle;
+ }
+ }
+ return this;
+ }
+
+ const currentParagraph = this._data.body?.paragraphs?.at(-1);
+ const currentParagraphStyle = Tools.deepClone(currentParagraph?.paragraphStyle);
+ const currentParagraphBullet = Tools.deepClone(currentParagraph?.bullet);
+ const startIndex = Math.max(0, (this._data.body?.dataStream.length ?? 2) - 2);
+ this.insertRichText(startIndex, RichTextValue.create({
+ id: 'd',
+ documentStyle: {},
+ body: {
+ dataStream: '\r',
+ paragraphs: [{
+ startIndex: 0,
+ paragraphId: createParagraphId(new Set()),
+ paragraphStyle: currentParagraphStyle,
+ bullet: currentParagraphBullet,
+ }],
+ },
+ }));
+ const nextParagraph = this._data.body?.paragraphs?.at(-1);
+ if (nextParagraphStyle) {
+ if (nextParagraph) {
+ nextParagraph.paragraphStyle = nextParagraphStyle;
+ }
+ } else if (nextParagraph) {
+ delete nextParagraph.paragraphStyle;
+ }
+ if (nextParagraph) {
+ delete nextParagraph.bullet;
+ }
+
+ return this;
+ }
+
/**
* Inserts text into the rich text builder at the specified start position
* @param start The start position of the text to insert
diff --git a/packages/core/src/facade/__tests__/f-enum.spec.ts b/packages/core/src/facade/__tests__/f-enum.spec.ts
index 9547136aad..6febf219c5 100644
--- a/packages/core/src/facade/__tests__/f-enum.spec.ts
+++ b/packages/core/src/facade/__tests__/f-enum.spec.ts
@@ -39,9 +39,12 @@ import {
LifecycleStages,
LocaleType,
MentionType,
+ NumberUnitType,
+ PresetListType,
ProtectionType,
RelativeDate,
SheetTypes,
+ SpacingRule,
TextDecoration,
TextDirection,
ThemeColorType,
@@ -72,6 +75,9 @@ describe('FEnum', () => {
expect(facadeEnum.BaselineOffset).toBe(BaselineOffset);
expect(facadeEnum.BooleanNumber).toBe(BooleanNumber);
expect(facadeEnum.HorizontalAlign).toBe(HorizontalAlign);
+ expect(facadeEnum.SpacingRule).toBe(SpacingRule);
+ expect(facadeEnum.NumberUnitType).toBe(NumberUnitType);
+ expect(facadeEnum.PresetListType).toBe(PresetListType);
expect(facadeEnum.TextDecoration).toBe(TextDecoration);
expect(facadeEnum.TextDirection).toBe(TextDirection);
expect(facadeEnum.VerticalAlign).toBe(VerticalAlign);
diff --git a/packages/core/src/facade/f-enum.ts b/packages/core/src/facade/f-enum.ts
index aa1b9f26d2..33aae61601 100644
--- a/packages/core/src/facade/f-enum.ts
+++ b/packages/core/src/facade/f-enum.ts
@@ -16,7 +16,7 @@
/* eslint-disable ts/explicit-function-return-type */
-import { AbsoluteRefType, AutoFillSeries, BaselineOffset, BooleanNumber, BorderStyleTypes, BorderType, ColorType, CommandType, CommonHideTypes, CopyPasteType, DataValidationErrorStyle, DataValidationOperator, DataValidationRenderMode, DataValidationStatus, DataValidationType, DeleteDirection, DeveloperMetadataVisibility, Dimension, Direction, HorizontalAlign, ImageSourceType, InterpolationPointType, LifecycleStages, LocaleType, MentionType, ProtectionType, RelativeDate, SheetTypes, TextDecoration, TextDirection, ThemeColorType, UniverInstanceType, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import { AbsoluteRefType, AutoFillSeries, BaselineOffset, BooleanNumber, BorderStyleTypes, BorderType, ColorType, CommandType, CommonHideTypes, CopyPasteType, DataValidationErrorStyle, DataValidationOperator, DataValidationRenderMode, DataValidationStatus, DataValidationType, DeleteDirection, DeveloperMetadataVisibility, Dimension, Direction, HorizontalAlign, ImageSourceType, InterpolationPointType, LifecycleStages, LocaleType, MentionType, NumberUnitType, PresetListType, ProtectionType, RelativeDate, SheetTypes, SpacingRule, TextDecoration, TextDirection, ThemeColorType, UniverInstanceType, VerticalAlign, WrapStrategy } from '@univerjs/core';
/**
* @hideconstructor
@@ -207,6 +207,45 @@ export class FEnum {
return HorizontalAlign;
}
+ /**
+ * Paragraph line-height interpretation modes
+ *
+ * @example
+ * ```ts
+ * console.log(univerAPI.Enum.SpacingRule.EXACT);
+ * ```
+ */
+ get SpacingRule() {
+ return SpacingRule;
+ }
+
+ /**
+ * Units accepted by document lengths such as paragraph indentation and spacing
+ *
+ * Agent-facing rich-text helpers accept plain numbers as document points, so this enum is only needed when an
+ * explicit alternative unit is required.
+ *
+ * @example
+ * ```ts
+ * console.log(univerAPI.Enum.NumberUnitType.POINT);
+ * ```
+ */
+ get NumberUnitType() {
+ return NumberUnitType;
+ }
+
+ /**
+ * Preset ordered, unordered, and checklist styles used by rich-text list items
+ *
+ * @example
+ * ```ts
+ * console.log(univerAPI.Enum.PresetListType.BULLET_LIST);
+ * ```
+ */
+ get PresetListType() {
+ return PresetListType;
+ }
+
/**
* Different text decoration styles
*