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(core): improve rich text builder consistency (#7410)

Univer891a0c445369
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 02a1676e3c..fefb4972af 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
@@ -225,6 +225,16 @@ describe('RichTextValue', () => {
expect(richText.toPlainText()).toBe('Hello World\nNew Line');
});
+ it('should preserve control characters supplied through the raw document-data boundary', () => {
+ const richText = RichTextValue.createByBody({
+ dataStream: 'A\nB\r\n',
+ paragraphs: [{ startIndex: 3, paragraphId: 'paragraph-1' }],
+ });
+
+ expect(richText.getData().body?.dataStream).toBe('A\nB\r\n');
+ expect(richText.getData().body?.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([3]);
+ });
+
it('should get paragraph style', () => {
const paragraphStyle = {
horizontalAlign: HorizontalAlign.CENTER,
@@ -276,6 +286,29 @@ describe('RichTextValue', () => {
expect(runs[0].ts?.getValue()).toEqual(textRun.ts);
});
+ it('should expose complete paragraph runs without requiring copy', () => {
+ const richText = RichTextValue.createByBody({
+ dataStream: 'Unstyled\rSecond\r\n',
+ textRuns: [],
+ paragraphs: [
+ { startIndex: 8, paragraphId: 'paragraph-1' },
+ { startIndex: 15, paragraphId: 'paragraph-2' },
+ ],
+ });
+
+ const paragraphs = richText.getParagraphs();
+ const copiedParagraphs = richText.copy().getParagraphs();
+
+ expect(paragraphs.map((paragraph) => paragraph.toPlainText())).toEqual(['Unstyled', 'Second']);
+ expect(paragraphs.map((paragraph) => paragraph.getTextRuns().map(({ st, ed }) => ({ st, ed })))).toEqual([
+ [{ st: 0, ed: 8 }],
+ [{ st: 0, ed: 6 }],
+ ]);
+ expect(paragraphs.map((paragraph) => paragraph.getTextRuns().length)).toEqual(
+ copiedParagraphs.map((paragraph) => paragraph.getTextRuns().length)
+ );
+ });
+
it('should get links', () => {
const link = {
startIndex: 0,
@@ -391,6 +424,17 @@ describe('RichTextBuilder', () => {
expect(data.body?.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([5, 12, 18, 25]);
});
+ it('should treat an inserted carriage return as a strict document paragraph break', () => {
+ const builder = RichTextBuilder.create()
+ .span('AB', {})
+ .insertText(1, '\r');
+
+ expect(builder.getData().body?.dataStream).toBe('A\rB\r\n');
+ expect(builder.getData().body?.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([1, 3]);
+ expect(builder.toPlainText()).toBe('A\nB');
+ expect(builder.getParagraphs().map((paragraph) => paragraph.getText())).toEqual(['A', 'B']);
+ });
+
it('should keep multiline span styles aligned with normalized paragraphs', () => {
const data = RichTextBuilder.create()
.text('A')
@@ -445,6 +489,15 @@ describe('RichTextBuilder', () => {
]);
});
+ it('should append an unstyled span when style is omitted', () => {
+ const data = RichTextBuilder.create()
+ .span('Text')
+ .getData();
+
+ expect(data.body?.dataStream).toBe('Text\r\n');
+ expect(data.body?.textRuns).toEqual([]);
+ });
+
it('should build inline code as a text style', () => {
const builder = RichTextBuilder.create()
.text('Run ')
@@ -671,6 +724,18 @@ describe('RichTextBuilder', () => {
expect(() => run.setText('First\nSecond')).toThrow(RangeError);
expect(run.getText()).toBe('Original');
});
+
+ it('invalidates existing child handles after a direct builder edit', () => {
+ const builder = RichTextBuilder.create().span('AB', {});
+ const paragraph = builder.getParagraphs()[0];
+ const run = paragraph.getTextRuns()[0];
+
+ builder.insertText(0, 'X');
+
+ expect(builder.getTextRuns().map((item) => item.getText())).toEqual(['XAB']);
+ expect(() => run.getText()).toThrow('Rich text child handle is no longer valid.');
+ expect(() => paragraph.getText()).toThrow('Rich text child handle is no longer valid.');
+ });
});
describe('rich text insertion', () => {
@@ -724,6 +789,21 @@ describe('RichTextBuilder', () => {
expect(builder.getData().body!.dataStream).toBe('Hello World\r\n');
});
+
+ it('should delete the requested number of characters from the end', () => {
+ const builder = RichTextBuilder.create()
+ .insertText('ABCDE')
+ .delete(2);
+
+ expect(builder.getData().body!.dataStream).toBe('ABC\r\n');
+ });
+
+ it('should clamp end deletion to content and reject negative counts', () => {
+ const builder = RichTextBuilder.create().insertText('ABC');
+
+ expect(() => builder.delete(-1)).toThrow(RangeError);
+ expect(builder.delete(10).getData().body!.dataStream).toBe('\r\n');
+ });
});
describe('style management', () => {
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 62895fd563..773ff5425e 100644
--- a/packages/core/src/docs/data-model/rich-text-builder.ts
+++ b/packages/core/src/docs/data-model/rich-text-builder.ts
@@ -1899,14 +1899,20 @@ export class RichTextValue {
* ```
*/
getParagraphs(): RichTextValue[] {
- const paragraphs = this._data.body?.paragraphs ?? [];
+ const body = this._data.body;
+ if (!body) {
+ return [];
+ }
- let start = 0;
- return paragraphs.map((paragraph) => {
- const sub = this.slice(start, paragraph.startIndex);
- start = paragraph.startIndex;
- return sub;
- });
+ const startOffsets = getParagraphContentStartOffsets(body);
+ return (body.paragraphs ?? []).map((paragraph) => RichTextBuilder.create(createParagraphSnapshot(
+ this._data,
+ paragraph.paragraphId,
+ {
+ startOffset: startOffsets.get(paragraph.startIndex) ?? 0,
+ endOffset: paragraph.startIndex,
+ }
+ )));
}
/**
@@ -2001,6 +2007,7 @@ export class RichTextBuilder extends RichTextValue {
private _doc: DocumentDataModel;
private readonly _trackedRanges = new Set<IMutableRichTextRange>();
+ private _childHandleRevision = 0;
constructor(data: IDocumentData) {
super(data);
@@ -2010,8 +2017,10 @@ export class RichTextBuilder extends RichTextValue {
/**
* Returns editable paragraph handles backed by this detached rich-text builder.
*
- * Paragraph boundaries come from the document model rather than splitting plain text. Each handle stays aligned
- * when text in this builder grows or shrinks, so callers can safely iterate from the first paragraph to the last.
+ * Paragraph boundaries come from the document model rather than splitting plain text. Handles stay aligned across
+ * edits made through their child run handles, so callers can safely iterate from the first paragraph to the last.
+ * Direct builder edits that change text or run boundaries invalidate previously returned paragraph and run handles;
+ * query them again after calling methods such as `insertText()`, `setStyle()`, `setLink()`, or `delete()`.
*
* @returns Editable paragraphs in document order.
* @example
@@ -2113,7 +2122,8 @@ export class RichTextBuilder extends RichTextValue {
this._trackRange(startOffset, endOffset),
sourceRun?.ts,
sourceRun?.sId,
- Boolean(sourceRun)
+ Boolean(sourceRun),
+ this._childHandleRevision
));
}
@@ -2188,7 +2198,19 @@ export class RichTextBuilder extends RichTextValue {
}
private _createParagraphBuilder(paragraphId: string, startOffset: number, endOffset: number): RichTextParagraphBuilder {
- return new RichTextParagraphBuilder(this, paragraphId, this._trackRange(startOffset, endOffset));
+ return new RichTextParagraphBuilder(
+ this,
+ paragraphId,
+ this._trackRange(startOffset, endOffset),
+ this._childHandleRevision
+ );
+ }
+
+ /** @internal */
+ _assertChildHandleRevision(revision: number): void {
+ if (revision !== this._childHandleRevision) {
+ throw new Error('Rich text child handle is no longer valid.');
+ }
}
private _trackRange(startOffset: number, endOffset: number): IMutableRichTextRange {
@@ -2216,6 +2238,11 @@ export class RichTextBuilder extends RichTextValue {
}
}
+ private _invalidateChildHandles(): void {
+ this._childHandleRevision++;
+ this._trackedRanges.clear();
+ }
+
/**
* Appends plain text to the rich text.
*
@@ -2342,14 +2369,15 @@ export class RichTextBuilder extends RichTextValue {
}
/**
- * Appends one text span with explicit style.
+ * Appends one text span with an optional 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.
+ * @param style Optional text style for this span. When omitted, the span is appended as unstyled text. 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
@@ -2358,12 +2386,12 @@ export class RichTextBuilder extends RichTextValue {
* .span('Important', { bold: true, italic: true, color: '#d92d20' });
* ```
*/
- span(text: string, style: IRichTextSpanStyle): RichTextBuilder {
+ span(text: string, style?: IRichTextSpanStyle): RichTextBuilder {
if (!text) {
return this;
}
- return this.insertText(text, normalizeRichTextSpanStyle(style));
+ return style ? this.insertText(text, normalizeRichTextSpanStyle(style)) : this.insertText(text);
}
/**
@@ -2596,6 +2624,7 @@ export class RichTextBuilder extends RichTextValue {
}
TextX.apply(this._doc.getBody()!, textX.serialize());
+ this._invalidateChildHandles();
return this;
}
@@ -2643,6 +2672,7 @@ export class RichTextBuilder extends RichTextValue {
}
TextX.apply(this._doc.getBody()!, textX.serialize());
+ this._invalidateChildHandles();
return this;
}
@@ -2670,11 +2700,37 @@ export class RichTextBuilder extends RichTextValue {
*/
delete(start: number, count: number): RichTextBuilder;
delete(start: number, count?: number): RichTextBuilder {
- // Implementation logic here
- if (count !== undefined) {
- if (!count) return this;
- const actions = BuildTextUtils.selection.delete([{ startOffset: start, endOffset: start + count, collapsed: true }], this._data.body!);
+ const terminalTokenLength =
+ DataStreamTreeTokenType.PARAGRAPH.length + DataStreamTreeTokenType.SECTION_BREAK.length;
+ const contentLength = Math.max(
+ 0,
+ (this._data.body?.dataStream.length ?? terminalTokenLength) - terminalTokenLength
+ );
+ let startOffset: number;
+ let deleteCount: number;
+
+ if (count === undefined) {
+ if (start < 0) {
+ throw new RangeError('Delete count cannot be negative.');
+ }
+ deleteCount = Math.min(start, contentLength);
+ startOffset = contentLength - deleteCount;
+ } else {
+ if (start < 0 || count < 0) {
+ throw new RangeError('Delete range cannot be negative.');
+ }
+ startOffset = Math.min(start, contentLength);
+ deleteCount = Math.min(count, contentLength - startOffset);
+ }
+
+ if (deleteCount > 0) {
+ const actions = BuildTextUtils.selection.delete([{
+ startOffset,
+ endOffset: startOffset + deleteCount,
+ collapsed: true,
+ }], this._data.body!);
TextX.apply(this._doc.getBody()!, actions);
+ this._invalidateChildHandles();
}
return this;
}
@@ -2702,6 +2758,7 @@ export class RichTextBuilder extends RichTextValue {
};
const actions = BuildTextUtils.selection.retain([{ startOffset: start, endOffset: end, collapsed: true }], newBody);
TextX.apply(this._doc.getBody()!, actions);
+ this._invalidateChildHandles();
return this;
}
@@ -2731,6 +2788,7 @@ export class RichTextBuilder extends RichTextValue {
throw new Error('Insert text failed, please check.');
}
TextX.apply(this._doc.getBody()!, textX.serialize());
+ this._invalidateChildHandles();
return this;
}
@@ -2782,6 +2840,7 @@ export class RichTextBuilder extends RichTextValue {
*/
cancelLink(start: number, end: number): RichTextBuilder;
cancelLink(start: number | string, end?: number): RichTextBuilder {
+ let changed = false;
if (typeof start === 'string') {
const textX = BuildTextUtils.customRange.delete({
rangeId: start,
@@ -2791,6 +2850,7 @@ export class RichTextBuilder extends RichTextValue {
throw new Error('Insert text failed, please check.');
}
TextX.apply(this._doc.getBody()!, textX.serialize());
+ changed = true;
} else {
const slice = this.slice(start as number, end as number);
slice.getLinks().forEach((l) => {
@@ -2802,9 +2862,14 @@ export class RichTextBuilder extends RichTextValue {
throw new Error('Insert text failed, please check.');
}
TextX.apply(this._doc.getBody()!, textX.serialize());
+ changed = true;
});
}
+ if (changed) {
+ this._invalidateChildHandles();
+ }
+
return this;
}
@@ -2917,18 +2982,21 @@ export class RichTextParagraphBuilder extends RichTextValue {
constructor(
private readonly _owner: RichTextBuilder,
private readonly _paragraphId: string,
- private readonly _range: IMutableRichTextRange
+ private readonly _range: IMutableRichTextRange,
+ private readonly _revision: number
) {
super(createParagraphSnapshot(_owner.getData(), _paragraphId, _range));
}
/** Returns the persisted paragraph id. */
getId(): string {
+ this._assertActive();
return this._paragraphId;
}
/** Returns the current paragraph range without its trailing paragraph marker. */
getRange(): IRichTextRange {
+ this._assertActive();
return { ...this._range };
}
@@ -2942,6 +3010,7 @@ export class RichTextParagraphBuilder extends RichTextValue {
* ```
*/
getText(): string {
+ this._assertActive();
const dataStream = this._owner.getData().body?.dataStream ?? '';
return dataStream.slice(this._range.startOffset, this._range.endOffset);
}
@@ -2955,18 +3024,22 @@ export class RichTextParagraphBuilder extends RichTextValue {
* @returns Editable text runs in document order.
*/
override getTextRuns(): RichTextRunBuilder[] {
+ this._assertActive();
return this._owner._createTextRunBuilders(this._range);
}
override getParagraphStyle(): ParagraphStyleValue {
+ this._assertActive();
return ParagraphStyleValue.create(this._getParagraph().paragraphStyle);
}
override getParagraphBullet() {
+ this._assertActive();
return this._getParagraph().bullet;
}
override getLinks() {
+ this._assertActive();
return this.getData().body?.customRanges?.filter((range) => range.rangeType === CustomRangeType.HYPERLINK) ?? [];
}
@@ -2976,6 +3049,7 @@ export class RichTextParagraphBuilder extends RichTextValue {
}
override getData(): IDocumentData {
+ this._assertActive();
return createParagraphSnapshot(this._owner.getData(), this._paragraphId, this._range);
}
@@ -2990,6 +3064,10 @@ export class RichTextParagraphBuilder extends RichTextValue {
}
return paragraph;
}
+
+ private _assertActive(): void {
+ this._owner._assertChildHandleRevision(this._revision);
+ }
}
/**
@@ -3007,36 +3085,43 @@ export class RichTextRunBuilder {
private readonly _range: IMutableRichTextRange,
private readonly _textStyle: ITextStyle | undefined,
private readonly _styleId: string | undefined,
- private readonly _hasExplicitTextStyle: boolean
+ private readonly _hasExplicitTextStyle: boolean,
+ private readonly _revision: number
) {}
/** Inclusive start offset, kept for compatibility with existing `getTextRuns()` callers. */
get st(): number {
+ this._assertActive();
return this._range.startOffset;
}
/** Exclusive end offset, automatically updated after text replacement. */
get ed(): number {
+ this._assertActive();
return this._range.endOffset;
}
/** Optional persisted style id. This is not a stable run identity. */
get sId(): string | undefined {
+ this._assertActive();
return this._styleId;
}
/** Existing text-style value property exposed by `getTextRuns()`. */
get ts(): TextStyleValue | null {
+ this._assertActive();
return this._textStyle ? TextStyleValue.create(this._textStyle) : null;
}
/** Returns the current run range. */
getRange(): IRichTextRange {
+ this._assertActive();
return { ...this._range };
}
/** Returns the current run text. */
getText(): string {
+ this._assertActive();
const dataStream = this._owner.getData().body?.dataStream ?? '';
return dataStream.slice(this._range.startOffset, this._range.endOffset);
}
@@ -3048,6 +3133,7 @@ export class RichTextRunBuilder {
/** Returns whether this segment is backed by an explicit document text run. */
hasTextStyle(): boolean {
+ this._assertActive();
return this._hasExplicitTextStyle;
}
@@ -3076,9 +3162,7 @@ export class RichTextRunBuilder {
* ```
*/
setText(text: string): this {
- if (!this._active) {
- throw new Error('Rich text run handle is no longer valid.');
- }
+ this._assertActive();
this._owner._replaceTextRun(
this._range,
text,
@@ -3091,6 +3175,13 @@ export class RichTextRunBuilder {
}
return this;
}
+
+ private _assertActive(): void {
+ if (!this._active) {
+ throw new Error('Rich text run handle is no longer valid.');
+ }
+ this._owner._assertChildHandleRevision(this._revision);
+ }
}
function createParagraphSnapshot(