From 8ec51b3f13ff4f3375d679888ee00502beba538d Mon Sep 17 00:00:00 2001 From: Jiuqing Song Date: Mon, 20 May 2024 14:03:42 -0700 Subject: [PATCH 1/7] Content Model Cache improvement - Step 1: Introduce Readonly types and mutate utility (#2629) * Readonly types (3rd try * Improve * fix build * Improve * improve * Improve * Add shallow mutable type * improve * Improve * improve * improve * add test * improve * improve * improve --- .../roosterjs-content-model-dom/lib/index.ts | 1 + .../lib/modelApi/common/mutate.ts | 107 ++++++++ .../lib/modelApi/editing/cloneModel.ts | 3 +- .../modelApi/editing/getSegmentTextFormat.ts | 3 +- .../test/modelApi/common/mutateTest.ts | 235 ++++++++++++++++++ .../contentModel/block/ContentModelBlock.ts | 56 ++++- .../block/ContentModelBlockBase.ts | 55 +++- .../contentModel/block/ContentModelDivider.ts | 28 ++- .../block/ContentModelParagraph.ts | 71 +++++- .../contentModel/block/ContentModelTable.ts | 58 ++++- .../block/ContentModelTableRow.ts | 54 +++- .../blockGroup/ContentModelBlockGroup.ts | 50 +++- .../blockGroup/ContentModelBlockGroupBase.ts | 47 +++- .../blockGroup/ContentModelDocument.ts | 41 ++- .../blockGroup/ContentModelFormatContainer.ts | 52 +++- .../blockGroup/ContentModelGeneralBlock.ts | 58 ++++- .../blockGroup/ContentModelListItem.ts | 64 ++++- .../blockGroup/ContentModelTableCell.ts | 63 ++++- .../lib/contentModel/common/MutableMark.ts | 73 ++++++ .../lib/contentModel/common/MutableType.ts | 101 ++++++++ .../lib/contentModel/common/Selectable.ts | 24 +- .../decorator/ContentModelCode.ts | 19 +- .../decorator/ContentModelDecorator.ts | 14 +- .../decorator/ContentModelLink.ts | 24 +- .../decorator/ContentModelListLevel.ts | 38 ++- .../ContentModelParagraphDecorator.ts | 33 ++- .../format/ContentModelWithDataset.ts | 27 +- .../format/ContentModelWithFormat.ts | 10 + .../format/metadata/DatasetFormat.ts | 5 + .../contentModel/segment/ContentModelBr.ts | 10 +- .../segment/ContentModelGeneralSegment.ts | 32 ++- .../contentModel/segment/ContentModelImage.ts | 32 ++- .../segment/ContentModelSegment.ts | 39 ++- .../segment/ContentModelSegmentBase.ts | 75 +++++- .../segment/ContentModelSelectionMarker.ts | 11 +- .../contentModel/segment/ContentModelText.ts | 21 +- .../lib/index.ts | 173 ++++++++++--- 37 files changed, 1636 insertions(+), 171 deletions(-) create mode 100644 packages/roosterjs-content-model-dom/lib/modelApi/common/mutate.ts create mode 100644 packages/roosterjs-content-model-dom/test/modelApi/common/mutateTest.ts create mode 100644 packages/roosterjs-content-model-types/lib/contentModel/common/MutableMark.ts create mode 100644 packages/roosterjs-content-model-types/lib/contentModel/common/MutableType.ts diff --git a/packages/roosterjs-content-model-dom/lib/index.ts b/packages/roosterjs-content-model-dom/lib/index.ts index d2f8789135a..d871e3d46f2 100644 --- a/packages/roosterjs-content-model-dom/lib/index.ts +++ b/packages/roosterjs-content-model-dom/lib/index.ts @@ -55,6 +55,7 @@ export { createDivider } from './modelApi/creators/createDivider'; export { createListLevel } from './modelApi/creators/createListLevel'; export { createEmptyModel } from './modelApi/creators/createEmptyModel'; +export { mutateBlock, mutateSegments, mutateSegment } from './modelApi/common/mutate'; export { addBlock } from './modelApi/common/addBlock'; export { addCode } from './modelApi/common/addDecorators'; export { addLink } from './modelApi/common/addDecorators'; diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/common/mutate.ts b/packages/roosterjs-content-model-dom/lib/modelApi/common/mutate.ts new file mode 100644 index 00000000000..e2ce4bc59f3 --- /dev/null +++ b/packages/roosterjs-content-model-dom/lib/modelApi/common/mutate.ts @@ -0,0 +1,107 @@ +import type { + MutableType, + ReadonlyContentModelBlock, + ReadonlyContentModelBlockGroup, + ReadonlyContentModelListItem, + ReadonlyContentModelParagraph, + ReadonlyContentModelSegment, + ReadonlyContentModelTable, + ShallowMutableContentModelParagraph, + ShallowMutableContentModelSegment, +} from 'roosterjs-content-model-types'; + +/** + * Convert a readonly block to mutable block, clear cached element if exist + * @param block The block to convert from + * @returns The same block object of its related mutable type + */ +export function mutateBlock( + block: T +): MutableType { + if (block.cachedElement) { + delete block.cachedElement; + } + + if (isTable(block)) { + block.rows.forEach(row => { + delete row.cachedElement; + }); + } else if (isListItem(block)) { + block.levels.forEach(level => delete level.cachedElement); + } + + const result = (block as unknown) as MutableType; + + return result; +} + +/** + * Convert segments of a readonly paragraph to be mutable. + * Segments that are not belong to the given paragraph will be skipped + * @param paragraph The readonly paragraph to convert from + * @param segments The segments to convert from + */ +export function mutateSegments( + paragraph: ReadonlyContentModelParagraph, + segments: ReadonlyContentModelSegment[] +): [ShallowMutableContentModelParagraph, ShallowMutableContentModelSegment[], number[]] { + const mutablePara = mutateBlock(paragraph); + const result: [ + ShallowMutableContentModelParagraph, + ShallowMutableContentModelSegment[], + number[] + ] = [mutablePara, [], []]; + + if (segments) { + segments.forEach(segment => { + const index = paragraph.segments.indexOf(segment); + + if (index >= 0) { + result[1].push(mutablePara.segments[index]); + result[2].push(index); + } + }); + } + + return result; +} + +/** + * Convert a readonly segment to be mutable, together with its owner paragraph + * If the segment does not belong to the given paragraph, return null for the segment + * @param paragraph The readonly paragraph to convert from + * @param segment The segment to convert from + */ +export function mutateSegment( + paragraph: ReadonlyContentModelParagraph, + segment: T, + callback?: ( + segment: MutableType, + paragraph: ShallowMutableContentModelParagraph, + index: number + ) => void +): [ShallowMutableContentModelParagraph, MutableType | null, number] { + const [mutablePara, mutableSegments, indexes] = mutateSegments(paragraph, [segment]); + const mutableSegment = + (mutableSegments[0] as ReadonlyContentModelSegment) == segment + ? (mutableSegments[0] as MutableType) + : null; + + if (callback && mutableSegment) { + callback(mutableSegments[0] as MutableType, mutablePara, indexes[0]); + } + + return [mutablePara, mutableSegment, indexes[0] ?? -1]; +} + +function isTable( + obj: ReadonlyContentModelBlockGroup | ReadonlyContentModelBlock +): obj is ReadonlyContentModelTable { + return (obj as ReadonlyContentModelTable).blockType == 'Table'; +} + +function isListItem( + obj: ReadonlyContentModelBlockGroup | ReadonlyContentModelBlock +): obj is ReadonlyContentModelListItem { + return (obj as ReadonlyContentModelListItem).blockGroupType == 'ListItem'; +} diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/editing/cloneModel.ts b/packages/roosterjs-content-model-dom/lib/modelApi/editing/cloneModel.ts index 2bf5dc15344..95ee0cee0ed 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/editing/cloneModel.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/editing/cloneModel.ts @@ -265,12 +265,13 @@ function cloneListItem( item: ContentModelListItem, options: CloneModelOptions ): ContentModelListItem { - const { formatHolder, levels } = item; + const { formatHolder, levels, cachedElement } = item; return Object.assign( { formatHolder: cloneSelectionMarker(formatHolder), levels: levels.map(cloneListLevel), + cachedElement: handleCachedElement(cachedElement, 'cache', options), }, cloneBlockBase(item), cloneBlockGroupBase(item, options) diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/editing/getSegmentTextFormat.ts b/packages/roosterjs-content-model-dom/lib/modelApi/editing/getSegmentTextFormat.ts index c8928b96cf9..cd91dbbde22 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/editing/getSegmentTextFormat.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/editing/getSegmentTextFormat.ts @@ -22,9 +22,10 @@ export function getSegmentTextFormat(segment: ContentModelSegment): ContentModel } const removeUndefinedValues = (format: ContentModelSegmentFormat): ContentModelSegmentFormat => { - const textFormat: Record = {}; + const textFormat: Record = {}; Object.keys(format).filter(key => { const value = format[key as keyof ContentModelSegmentFormat]; + if (value !== undefined) { textFormat[key] = value; } diff --git a/packages/roosterjs-content-model-dom/test/modelApi/common/mutateTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/common/mutateTest.ts new file mode 100644 index 00000000000..d4b31594cc9 --- /dev/null +++ b/packages/roosterjs-content-model-dom/test/modelApi/common/mutateTest.ts @@ -0,0 +1,235 @@ +import { createContentModelDocument } from '../../../lib/modelApi/creators/createContentModelDocument'; +import { createListItem } from '../../../lib/modelApi/creators/createListItem'; +import { createListLevel } from '../../../lib/modelApi/creators/createListLevel'; +import { createParagraph } from '../../../lib/modelApi/creators/createParagraph'; +import { createTable } from '../../../lib/modelApi/creators/createTable'; +import { createTableCell } from '../../../lib/modelApi/creators/createTableCell'; +import { createText } from '../../../lib/modelApi/creators/createText'; +import { mutateBlock, mutateSegment, mutateSegments } from '../../../lib/modelApi/common/mutate'; + +const mockedCache = 'CACHE' as any; + +describe('mutate', () => { + it('mutate a block without cache', () => { + const block = {} as any; + + const mutatedBlock = mutateBlock(block); + + expect(mutatedBlock).toBe(block); + expect(mutatedBlock).toEqual({} as any); + }); + + it('mutate a block with cache', () => { + const block = {} as any; + + block.cachedElement = mockedCache; + + const mutatedBlock = mutateBlock(block); + + expect(mutatedBlock).toBe(block); + expect(mutatedBlock).toEqual({} as any); + }); + + it('mutate a block group with cache', () => { + const doc = createContentModelDocument(); + const para = createParagraph(); + + doc.cachedElement = mockedCache; + para.cachedElement = mockedCache; + + doc.blocks.push(para); + + const mutatedBlock = mutateBlock(doc); + + expect(mutatedBlock).toBe(doc); + expect(mutatedBlock).toEqual({ + blockGroupType: 'Document', + blocks: [ + { + blockType: 'Paragraph', + segments: [], + format: {}, + cachedElement: mockedCache, + }, + ], + } as any); + }); + + it('mutate a table', () => { + const table = createTable(1); + const cell = createTableCell(); + const para = createParagraph(); + + table.cachedElement = mockedCache; + table.rows[0].cachedElement = mockedCache; + cell.cachedElement = mockedCache; + para.cachedElement = mockedCache; + + cell.blocks.push(para); + table.rows[0].cells.push(cell); + + const mutatedBlock = mutateBlock(table); + + expect(mutatedBlock).toBe(table); + expect(mutatedBlock).toEqual({ + blockType: 'Table', + rows: [ + { + cells: [ + { + blockGroupType: 'TableCell', + blocks: [ + { + blockType: 'Paragraph', + segments: [], + format: {}, + cachedElement: mockedCache, + }, + ], + format: {}, + spanLeft: false, + spanAbove: false, + isHeader: false, + dataset: {}, + cachedElement: mockedCache, + }, + ], + height: 0, + format: {}, + }, + ], + format: {}, + widths: [], + dataset: {}, + } as any); + }); + + it('mutate a list', () => { + const level = createListLevel('OL'); + const list = createListItem([level]); + const para = createParagraph(); + + level.cachedElement = mockedCache; + list.cachedElement = mockedCache; + para.cachedElement = mockedCache; + + list.blocks.push(para); + + const mutatedBlock = mutateBlock(list); + + expect(mutatedBlock).toBe(list); + expect(mutatedBlock).toEqual({ + blockType: 'BlockGroup', + format: {}, + blockGroupType: 'ListItem', + blocks: [ + { + blockType: 'Paragraph', + segments: [], + format: {}, + cachedElement: mockedCache, + }, + ], + levels: [{ listType: 'OL', format: {}, dataset: {} }], + formatHolder: { + segmentType: 'SelectionMarker', + isSelected: false, + format: {}, + }, + } as any); + }); +}); + +describe('mutateSegments', () => { + it('empty paragraph', () => { + const para = createParagraph(); + + para.cachedElement = mockedCache; + + const result = mutateSegments(para, []); + + expect(result).toEqual([para, [], []]); + expect(result[0].cachedElement).toBeUndefined(); + }); + + it('Paragraph with correct segments', () => { + const para = createParagraph(); + + para.cachedElement = mockedCache; + + const text1 = createText('test1'); + const text2 = createText('test2'); + const text3 = createText('test3'); + const text4 = createText('test4'); + + para.segments.push(text1, text2, text3, text4); + + const result = mutateSegments(para, [text2, text4]); + + expect(result).toEqual([para, [text2, text4], [1, 3]]); + expect(result[0].cachedElement).toBeUndefined(); + }); + + it('Paragraph with incorrect segments', () => { + const para = createParagraph(); + + para.cachedElement = mockedCache; + + const text1 = createText('test1'); + const text2 = createText('test2'); + const text3 = createText('test3'); + const text4 = createText('test4'); + + para.segments.push(text1, text2, text3); + + const result = mutateSegments(para, [text2, text4]); + + expect(result).toEqual([para, [text2], [1]]); + expect(result[0].cachedElement).toBeUndefined(); + }); +}); + +describe('mutateSegment', () => { + let callbackSpy: jasmine.Spy; + + beforeEach(() => { + callbackSpy = jasmine.createSpy('callback'); + }); + + it('Paragraph with correct segment', () => { + const para = createParagraph(); + + para.cachedElement = mockedCache; + + const text1 = createText('test1'); + const text2 = createText('test2'); + const text3 = createText('test3'); + + para.segments.push(text1, text2, text3); + + const result = mutateSegment(para, text2, callbackSpy); + + expect(result).toEqual([para, text2, 1]); + expect(result[0].cachedElement).toBeUndefined(); + expect(callbackSpy).toHaveBeenCalledTimes(1); + expect(callbackSpy).toHaveBeenCalledWith(text2, para, 1); + }); + + it('Paragraph with incorrect segment', () => { + const para = createParagraph(); + + para.cachedElement = mockedCache; + + const text1 = createText('test1'); + const text2 = createText('test2'); + const text3 = createText('test3'); + + para.segments.push(text1, text3); + + const result = mutateSegment(para, text2, callbackSpy); + + expect(result).toEqual([para, null, -1]); + expect(result[0].cachedElement).toBeUndefined(); + expect(callbackSpy).toHaveBeenCalledTimes(0); + }); +}); diff --git a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelBlock.ts b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelBlock.ts index 59179bdd73c..7ec515f4e77 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelBlock.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelBlock.ts @@ -1,10 +1,30 @@ -import type { ContentModelDivider } from './ContentModelDivider'; +import type { ContentModelDivider, ReadonlyContentModelDivider } from './ContentModelDivider'; import type { ContentModelEntity } from '../entity/ContentModelEntity'; -import type { ContentModelFormatContainer } from '../blockGroup/ContentModelFormatContainer'; -import type { ContentModelGeneralBlock } from '../blockGroup/ContentModelGeneralBlock'; -import type { ContentModelListItem } from '../blockGroup/ContentModelListItem'; -import type { ContentModelParagraph } from './ContentModelParagraph'; -import type { ContentModelTable } from './ContentModelTable'; +import type { + ContentModelFormatContainer, + ReadonlyContentModelFormatContainer, + ShallowMutableContentModelFormatContainer, +} from '../blockGroup/ContentModelFormatContainer'; +import type { + ContentModelGeneralBlock, + ReadonlyContentModelGeneralBlock, + ShallowMutableContentModelGeneralBlock, +} from '../blockGroup/ContentModelGeneralBlock'; +import type { + ContentModelListItem, + ReadonlyContentModelListItem, + ShallowMutableContentModelListItem, +} from '../blockGroup/ContentModelListItem'; +import type { + ContentModelParagraph, + ReadonlyContentModelParagraph, + ShallowMutableContentModelParagraph, +} from './ContentModelParagraph'; +import type { + ContentModelTable, + ReadonlyContentModelTable, + ShallowMutableContentModelTable, +} from './ContentModelTable'; /** * A union type of Content Model Block @@ -17,3 +37,27 @@ export type ContentModelBlock = | ContentModelParagraph | ContentModelEntity | ContentModelDivider; + +/** + * A union type of Content Model Block (Readonly) + */ +export type ReadonlyContentModelBlock = + | ReadonlyContentModelFormatContainer + | ReadonlyContentModelListItem + | ReadonlyContentModelGeneralBlock + | ReadonlyContentModelTable + | ReadonlyContentModelParagraph + | ContentModelEntity + | ReadonlyContentModelDivider; + +/** + * A union type of Content Model Block (Shallow mutable) + */ +export type ShallowMutableContentModelBlock = + | ShallowMutableContentModelFormatContainer + | ShallowMutableContentModelListItem + | ShallowMutableContentModelGeneralBlock + | ShallowMutableContentModelTable + | ShallowMutableContentModelParagraph + | ContentModelEntity + | ContentModelDivider; diff --git a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelBlockBase.ts b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelBlockBase.ts index 8e05b45151f..7fef63cb17a 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelBlockBase.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelBlockBase.ts @@ -1,16 +1,57 @@ +import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; +import type { MutableMark, ReadonlyMark, ShallowMutableMark } from '../common/MutableMark'; import type { ContentModelBlockFormat } from '../format/ContentModelBlockFormat'; import type { ContentModelBlockType } from './BlockType'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; /** - * Base type of a block + * Common part of base type of a block */ -export interface ContentModelBlockBase< - T extends ContentModelBlockType, - TFormat extends ContentModelBlockFormat = ContentModelBlockFormat -> extends ContentModelWithFormat { +export interface ContentModelBlockBaseCommon { /** * Type of this block */ - blockType: T; + readonly blockType: T; } + +/** + * Base type of a block + */ +export interface ContentModelBlockBase< + T extends ContentModelBlockType, + TFormat extends ContentModelBlockFormat = ContentModelBlockFormat, + TCacheElement extends HTMLElement = HTMLElement +> + extends MutableMark, + ContentModelBlockBaseCommon, + ContentModelWithFormat, + ContentModelBlockWithCache {} + +/** + * Base type of a block (Readonly) + */ +export interface ReadonlyContentModelBlockBase< + T extends ContentModelBlockType, + TFormat extends ContentModelBlockFormat = ContentModelBlockFormat, + TCacheElement extends HTMLElement = HTMLElement +> + extends ReadonlyMark, + ContentModelBlockBaseCommon, + ReadonlyContentModelWithFormat, + ContentModelBlockWithCache {} + +/** + * Base type of a block (Shallow mutable) + */ +export interface ShallowMutableContentModelBlockBase< + T extends ContentModelBlockType, + TFormat extends ContentModelBlockFormat = ContentModelBlockFormat, + TCacheElement extends HTMLElement = HTMLElement +> + extends ShallowMutableMark, + ContentModelBlockBaseCommon, + ContentModelWithFormat, + ContentModelBlockWithCache {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelDivider.ts b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelDivider.ts index 23fe4386273..c38c9d15734 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelDivider.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelDivider.ts @@ -1,15 +1,11 @@ -import type { ContentModelBlockBase } from './ContentModelBlockBase'; -import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; +import type { ContentModelBlockBase, ReadonlyContentModelBlockBase } from './ContentModelBlockBase'; import type { ContentModelDividerFormat } from '../format/ContentModelDividerFormat'; -import type { Selectable } from '../common/Selectable'; +import type { ReadonlySelectable, Selectable } from '../common/Selectable'; /** - * Content Model of horizontal divider + * Common part of Content Model of horizontal divider */ -export interface ContentModelDivider - extends Selectable, - ContentModelBlockWithCache, - ContentModelBlockBase<'Divider', ContentModelDividerFormat> { +export interface ContentModelDividerCommon { /** * Tag name of this element, either HR or DIV */ @@ -20,3 +16,19 @@ export interface ContentModelDivider */ size?: string; } + +/** + * Content Model of horizontal divider + */ +export interface ContentModelDivider + extends Selectable, + ContentModelDividerCommon, + ContentModelBlockBase<'Divider', ContentModelDividerFormat> {} + +/** + * Content Model of horizontal divider (Readonly) + */ +export interface ReadonlyContentModelDivider + extends ReadonlySelectable, + ReadonlyContentModelBlockBase<'Divider', ContentModelDividerFormat>, + Readonly {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelParagraph.ts b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelParagraph.ts index cb47999a4a4..94a46391352 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelParagraph.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelParagraph.ts @@ -1,14 +1,31 @@ -import type { ContentModelBlockBase } from './ContentModelBlockBase'; -import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; -import type { ContentModelParagraphDecorator } from '../decorator/ContentModelParagraphDecorator'; -import type { ContentModelSegment } from '../segment/ContentModelSegment'; +import type { ContentModelBlockBase, ReadonlyContentModelBlockBase } from './ContentModelBlockBase'; +import type { + ContentModelParagraphDecorator, + ReadonlyContentModelParagraphDecorator, +} from '../decorator/ContentModelParagraphDecorator'; +import type { + ContentModelSegment, + ReadonlyContentModelSegment, + ShallowMutableContentModelSegment, +} from '../segment/ContentModelSegment'; import type { ContentModelSegmentFormat } from '../format/ContentModelSegmentFormat'; +/** + * Common part of Content Model of Paragraph + */ +export interface ContentModelParagraphCommon { + /** + * Whether this block was created from a block HTML element or just some simple segment between other block elements. + * True means it doesn't have a related block element, false means it was from a block element + */ + isImplicit?: boolean; +} + /** * Content Model of Paragraph */ export interface ContentModelParagraph - extends ContentModelBlockWithCache, + extends ContentModelParagraphCommon, ContentModelBlockBase<'Paragraph'> { /** * Segments within this paragraph @@ -24,10 +41,48 @@ export interface ContentModelParagraph * Decorator info for this paragraph, used by heading and P tags */ decorator?: ContentModelParagraphDecorator; +} +/** + * Content Model of Paragraph (Readonly) + */ +export interface ReadonlyContentModelParagraph + extends ReadonlyContentModelBlockBase<'Paragraph'>, + Readonly { /** - * Whether this block was created from a block HTML element or just some simple segment between other block elements. - * True means it doesn't have a related block element, false means it was from a block element + * Segments within this paragraph */ - isImplicit?: boolean; + readonly segments: ReadonlyArray; + + /** + * Segment format on this paragraph. This is mostly used for default format + */ + readonly segmentFormat?: Readonly; + + /** + * Decorator info for this paragraph, used by heading and P tags + */ + readonly decorator?: ReadonlyContentModelParagraphDecorator; +} + +/** + * Content Model of Paragraph (Shallow mutable) + */ +export interface ShallowMutableContentModelParagraph + extends ContentModelParagraphCommon, + ContentModelBlockBase<'Paragraph'> { + /** + * Segments within this paragraph + */ + segments: ShallowMutableContentModelSegment[]; + + /** + * Segment format on this paragraph. This is mostly used for default format + */ + segmentFormat?: ContentModelSegmentFormat; + + /** + * Decorator info for this paragraph, used by heading and P tags + */ + decorator?: ContentModelParagraphDecorator; } diff --git a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelTable.ts b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelTable.ts index c9c70ebe6c4..741fd7f8abc 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelTable.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelTable.ts @@ -1,17 +1,27 @@ -import type { ContentModelBlockBase } from './ContentModelBlockBase'; -import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; +import type { + ContentModelBlockBase, + ReadonlyContentModelBlockBase, + ShallowMutableContentModelBlockBase, +} from './ContentModelBlockBase'; import type { ContentModelTableFormat } from '../format/ContentModelTableFormat'; -import type { ContentModelTableRow } from './ContentModelTableRow'; -import type { ContentModelWithDataset } from '../format/ContentModelWithDataset'; +import type { + ContentModelTableRow, + ReadonlyContentModelTableRow, + ShallowMutableContentModelTableRow, +} from './ContentModelTableRow'; +import type { + ContentModelWithDataset, + ReadonlyContentModelWithDataset, + ShallowMutableContentModelWithDataset, +} from '../format/ContentModelWithDataset'; import type { TableMetadataFormat } from '../format/metadata/TableMetadataFormat'; /** * Content Model of Table */ export interface ContentModelTable - extends ContentModelBlockBase<'Table', ContentModelTableFormat>, - ContentModelWithDataset, - ContentModelBlockWithCache { + extends ContentModelBlockBase<'Table', ContentModelTableFormat, HTMLTableElement>, + ContentModelWithDataset { /** * Widths of each column */ @@ -22,3 +32,37 @@ export interface ContentModelTable */ rows: ContentModelTableRow[]; } + +/** + * Content Model of Table (Readonly) + */ +export interface ReadonlyContentModelTable + extends ReadonlyContentModelBlockBase<'Table', ContentModelTableFormat, HTMLTableElement>, + ReadonlyContentModelWithDataset { + /** + * Widths of each column + */ + readonly widths: ReadonlyArray; + + /** + * Cells of this table + */ + readonly rows: ReadonlyArray; +} + +/** + * Content Model of Table (Shallow mutable) + */ +export interface ShallowMutableContentModelTable + extends ShallowMutableContentModelBlockBase<'Table', ContentModelTableFormat, HTMLTableElement>, + ShallowMutableContentModelWithDataset { + /** + * Widths of each column + */ + widths: number[]; + + /** + * Cells of this table + */ + rows: ShallowMutableContentModelTableRow[]; +} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelTableRow.ts b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelTableRow.ts index 7a5327feb01..3dd881f7309 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelTableRow.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/block/ContentModelTableRow.ts @@ -1,21 +1,63 @@ +import type { MutableMark, ReadonlyMark, ShallowMutableMark } from '../common/MutableMark'; import type { ContentModelBlockFormat } from '../format/ContentModelBlockFormat'; import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; -import type { ContentModelTableCell } from '../blockGroup/ContentModelTableCell'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; +import type { + ContentModelTableCell, + ReadonlyContentModelTableCell, +} from '../blockGroup/ContentModelTableCell'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; /** - * Content Model of Table + * Common part of Content Model of Table */ -export interface ContentModelTableRow - extends ContentModelBlockWithCache, - ContentModelWithFormat { +export interface ContentModelTableRowCommon { /** * Heights of each row */ height: number; +} +/** + * Content Model of Table + */ +export interface ContentModelTableRow + extends MutableMark, + ContentModelTableRowCommon, + ContentModelBlockWithCache, + ContentModelWithFormat { /** * Cells of this table */ cells: ContentModelTableCell[]; } + +/** + * Content Model of Table (Readonly) + */ +export interface ReadonlyContentModelTableRow + extends ReadonlyMark, + Readonly, + ContentModelBlockWithCache, + ReadonlyContentModelWithFormat { + /** + * Cells of this table + */ + readonly cells: ReadonlyArray; +} + +/** + * Content Model of Table (Readonly) + */ +export interface ShallowMutableContentModelTableRow + extends ShallowMutableMark, + ContentModelTableRowCommon, + ContentModelBlockWithCache, + ContentModelWithFormat { + /** + * Cells of this table + */ + cells: ReadonlyContentModelTableCell[]; +} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelBlockGroup.ts b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelBlockGroup.ts index 9462d998e10..d526e962738 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelBlockGroup.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelBlockGroup.ts @@ -1,8 +1,28 @@ -import type { ContentModelDocument } from './ContentModelDocument'; -import type { ContentModelFormatContainer } from './ContentModelFormatContainer'; -import type { ContentModelGeneralBlock } from './ContentModelGeneralBlock'; -import type { ContentModelListItem } from './ContentModelListItem'; -import type { ContentModelTableCell } from './ContentModelTableCell'; +import type { + ContentModelDocument, + ReadonlyContentModelDocument, + ShallowMutableContentModelDocument, +} from './ContentModelDocument'; +import type { + ContentModelFormatContainer, + ReadonlyContentModelFormatContainer, + ShallowMutableContentModelFormatContainer, +} from './ContentModelFormatContainer'; +import type { + ContentModelGeneralBlock, + ReadonlyContentModelGeneralBlock, + ShallowMutableContentModelGeneralBlock, +} from './ContentModelGeneralBlock'; +import type { + ContentModelListItem, + ReadonlyContentModelListItem, + ShallowMutableContentModelListItem, +} from './ContentModelListItem'; +import type { + ContentModelTableCell, + ReadonlyContentModelTableCell, + ShallowMutableContentModelTableCell, +} from './ContentModelTableCell'; /** * The union type of Content Model Block Group @@ -13,3 +33,23 @@ export type ContentModelBlockGroup = | ContentModelListItem | ContentModelTableCell | ContentModelGeneralBlock; + +/** + * The union type of Content Model Block Group (Readonly) + */ +export type ReadonlyContentModelBlockGroup = + | ReadonlyContentModelDocument + | ReadonlyContentModelFormatContainer + | ReadonlyContentModelListItem + | ReadonlyContentModelTableCell + | ReadonlyContentModelGeneralBlock; + +/** + * The union type of Content Model Block Group (Shallow mutable) + */ +export type ShallowMutableContentModelBlockGroup = + | ShallowMutableContentModelDocument + | ShallowMutableContentModelFormatContainer + | ShallowMutableContentModelListItem + | ShallowMutableContentModelTableCell + | ShallowMutableContentModelGeneralBlock; diff --git a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelBlockGroupBase.ts b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelBlockGroupBase.ts index 648f9b1bd70..3235a5e4acb 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelBlockGroupBase.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelBlockGroupBase.ts @@ -1,17 +1,56 @@ -import type { ContentModelBlock } from '../block/ContentModelBlock'; +import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; +import type { MutableMark, ReadonlyMark, ShallowMutableMark } from '../common/MutableMark'; +import type { ContentModelBlock, ReadonlyContentModelBlock } from '../block/ContentModelBlock'; import type { ContentModelBlockGroupType } from './BlockGroupType'; /** - * Base type of Content Model Block Group + * Common part of base type of Content Model Block Group */ -export interface ContentModelBlockGroupBase { +export interface ContentModelBlockGroupBaseCommon< + T extends ContentModelBlockGroupType, + TElement extends HTMLElement = HTMLElement +> extends ContentModelBlockWithCache { /** * Type of this block group */ - blockGroupType: T; + readonly blockGroupType: T; +} +/** + * Base type of Content Model Block Group + */ +export interface ContentModelBlockGroupBase< + T extends ContentModelBlockGroupType, + TElement extends HTMLElement = HTMLElement +> extends MutableMark, ContentModelBlockGroupBaseCommon { /** * Blocks under this group */ blocks: ContentModelBlock[]; } + +/** + * Base type of Content Model Block Group (Readonly) + */ +export interface ReadonlyContentModelBlockGroupBase< + T extends ContentModelBlockGroupType, + TElement extends HTMLElement = HTMLElement +> extends ReadonlyMark, ContentModelBlockGroupBaseCommon { + /** + * Blocks under this group + */ + readonly blocks: ReadonlyArray; +} + +/** + * Base type of Content Model Block Group (Shallow mutable) + */ +export interface ShallowMutableContentModelBlockGroupBase< + T extends ContentModelBlockGroupType, + TElement extends HTMLElement = HTMLElement +> extends ShallowMutableMark, ContentModelBlockGroupBaseCommon { + /** + * Blocks under this group + */ + blocks: ReadonlyContentModelBlock[]; +} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelDocument.ts b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelDocument.ts index 7f1eac6188c..0584de310d6 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelDocument.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelDocument.ts @@ -1,15 +1,44 @@ -import type { ContentModelBlockGroupBase } from './ContentModelBlockGroupBase'; +import type { + ContentModelBlockGroupBase, + ReadonlyContentModelBlockGroupBase, + ShallowMutableContentModelBlockGroupBase, +} from './ContentModelBlockGroupBase'; import type { ContentModelSegmentFormat } from '../format/ContentModelSegmentFormat'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; /** - * Content Model document entry point + * Common part of Content Model document entry point */ -export interface ContentModelDocument - extends ContentModelBlockGroupBase<'Document'>, - Partial> { +export interface ContentModelDocumentCommon { /** * Whether the selection in model (if any) is a revert selection (end is before start) */ hasRevertedRangeSelection?: boolean; } + +/** + * Content Model document entry point + */ +export interface ContentModelDocument + extends ContentModelDocumentCommon, + ContentModelBlockGroupBase<'Document'>, + Partial> {} + +/** + * Content Model document entry point (Readonly) + */ +export interface ReadonlyContentModelDocument + extends Readonly, + ReadonlyContentModelBlockGroupBase<'Document'>, + Partial> {} + +/** + * Content Model document entry point (Shallow mutable) + */ +export interface ShallowMutableContentModelDocument + extends ContentModelDocumentCommon, + ShallowMutableContentModelBlockGroupBase<'Document'>, + Partial> {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelFormatContainer.ts b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelFormatContainer.ts index 5abe704bdea..8ebcc01c06e 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelFormatContainer.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelFormatContainer.ts @@ -1,15 +1,19 @@ -import type { ContentModelBlockBase } from '../block/ContentModelBlockBase'; -import type { ContentModelBlockGroupBase } from './ContentModelBlockGroupBase'; -import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; +import type { + ContentModelBlockBase, + ReadonlyContentModelBlockBase, + ShallowMutableContentModelBlockBase, +} from '../block/ContentModelBlockBase'; +import type { + ContentModelBlockGroupBase, + ReadonlyContentModelBlockGroupBase, + ShallowMutableContentModelBlockGroupBase, +} from './ContentModelBlockGroupBase'; import type { ContentModelFormatContainerFormat } from '../format/ContentModelFormatContainerFormat'; /** - * Content Model of Format Container + * Common part of Content Model of Format Container */ -export interface ContentModelFormatContainer - extends ContentModelBlockWithCache, - ContentModelBlockGroupBase<'FormatContainer'>, - ContentModelBlockBase<'BlockGroup', ContentModelFormatContainerFormat> { +export interface ContentModelFormatContainerCommon { /** * Tag name of this container */ @@ -21,3 +25,35 @@ export interface ContentModelFormatContainer */ zeroFontSize?: boolean; } + +/** + * Content Model of Format Container + */ +export interface ContentModelFormatContainer + extends ContentModelFormatContainerCommon, + ContentModelBlockGroupBase<'FormatContainer'>, + ContentModelBlockBase<'BlockGroup', ContentModelFormatContainerFormat, HTMLElement> {} + +/** + * Content Model of Format Container (Readonly) + */ +export interface ReadonlyContentModelFormatContainer + extends Readonly, + ReadonlyContentModelBlockGroupBase<'FormatContainer'>, + ReadonlyContentModelBlockBase< + 'BlockGroup', + ContentModelFormatContainerFormat, + HTMLElement + > {} + +/** + * Content Model of Format Container (Shallow mutable) + */ +export interface ShallowMutableContentModelFormatContainer + extends ContentModelFormatContainerCommon, + ShallowMutableContentModelBlockGroupBase<'FormatContainer'>, + ShallowMutableContentModelBlockBase< + 'BlockGroup', + ContentModelFormatContainerFormat, + HTMLElement + > {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelGeneralBlock.ts b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelGeneralBlock.ts index ff3899baa4f..e6f577dc99b 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelGeneralBlock.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelGeneralBlock.ts @@ -1,18 +1,60 @@ -import type { ContentModelBlockBase } from '../block/ContentModelBlockBase'; +import type { + ContentModelBlockBase, + ReadonlyContentModelBlockBase, + ShallowMutableContentModelBlockBase, +} from '../block/ContentModelBlockBase'; import type { ContentModelBlockFormat } from '../format/ContentModelBlockFormat'; -import type { ContentModelBlockGroupBase } from './ContentModelBlockGroupBase'; +import type { + ContentModelBlockGroupBase, + ShallowMutableContentModelBlockGroupBase, + ReadonlyContentModelBlockGroupBase, +} from './ContentModelBlockGroupBase'; import type { ContentModelSegmentFormat } from '../format/ContentModelSegmentFormat'; -import type { Selectable } from '../common/Selectable'; +import type { + ReadonlySelectable, + Selectable, + ShallowMutableSelectable, +} from '../common/Selectable'; /** - * Content Model for general Block element + * Common part of Content Model for general Block element */ -export interface ContentModelGeneralBlock - extends Selectable, - ContentModelBlockGroupBase<'General'>, - ContentModelBlockBase<'BlockGroup', ContentModelBlockFormat & ContentModelSegmentFormat> { +export interface ContentModelGeneralBlockCommon { /** * A reference to original HTML node that this model was created from */ element: HTMLElement; } + +/** + * Content Model for general Block element + */ +export interface ContentModelGeneralBlock + extends Selectable, + ContentModelGeneralBlockCommon, + ContentModelBlockGroupBase<'General'>, + ContentModelBlockBase<'BlockGroup', ContentModelBlockFormat & ContentModelSegmentFormat> {} + +/** + * Content Model for general Block element (Readonly) + */ +export interface ReadonlyContentModelGeneralBlock + extends ReadonlySelectable, + Readonly, + ReadonlyContentModelBlockGroupBase<'General'>, + ReadonlyContentModelBlockBase< + 'BlockGroup', + ContentModelBlockFormat & ContentModelSegmentFormat + > {} + +/** + * Content Model for general Block element (Shallow mutable) + */ +export interface ShallowMutableContentModelGeneralBlock + extends ShallowMutableSelectable, + ContentModelGeneralBlockCommon, + ShallowMutableContentModelBlockGroupBase<'General'>, + ShallowMutableContentModelBlockBase< + 'BlockGroup', + ContentModelBlockFormat & ContentModelSegmentFormat + > {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelListItem.ts b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelListItem.ts index a7b7eabd5ff..42029807129 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelListItem.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelListItem.ts @@ -1,15 +1,67 @@ -import type { ContentModelBlockBase } from '../block/ContentModelBlockBase'; -import type { ContentModelBlockGroupBase } from './ContentModelBlockGroupBase'; +import type { + ContentModelBlockBase, + ReadonlyContentModelBlockBase, + ShallowMutableContentModelBlockBase, +} from '../block/ContentModelBlockBase'; +import type { + ContentModelBlockGroupBase, + ReadonlyContentModelBlockGroupBase, + ShallowMutableContentModelBlockGroupBase, +} from './ContentModelBlockGroupBase'; import type { ContentModelListItemFormat } from '../format/ContentModelListItemFormat'; -import type { ContentModelListLevel } from '../decorator/ContentModelListLevel'; -import type { ContentModelSelectionMarker } from '../segment/ContentModelSelectionMarker'; +import type { + ContentModelListLevel, + ReadonlyContentModelListLevel, +} from '../decorator/ContentModelListLevel'; +import type { + ContentModelSelectionMarker, + ReadonlyContentModelSelectionMarker, +} from '../segment/ContentModelSelectionMarker'; /** * Content Model of List Item */ export interface ContentModelListItem - extends ContentModelBlockGroupBase<'ListItem'>, - ContentModelBlockBase<'BlockGroup', ContentModelListItemFormat> { + extends ContentModelBlockGroupBase<'ListItem', HTMLLIElement>, + ContentModelBlockBase<'BlockGroup', ContentModelListItemFormat, HTMLLIElement> { + /** + * Type of this list, either ordered or unordered + */ + levels: ContentModelListLevel[]; + + /** + * A dummy segment to hold format of this list item + */ + formatHolder: ContentModelSelectionMarker; +} + +/** + * Content Model of List Item (Readonly) + */ +export interface ReadonlyContentModelListItem + extends ReadonlyContentModelBlockGroupBase<'ListItem', HTMLLIElement>, + ReadonlyContentModelBlockBase<'BlockGroup', ContentModelListItemFormat, HTMLLIElement> { + /** + * Type of this list, either ordered or unordered + */ + readonly levels: ReadonlyArray; + + /** + * A dummy segment to hold format of this list item + */ + readonly formatHolder: ReadonlyContentModelSelectionMarker; +} + +/** + * Content Model of List Item (Shallow mutable) + */ +export interface ShallowMutableContentModelListItem + extends ShallowMutableContentModelBlockGroupBase<'ListItem', HTMLLIElement>, + ShallowMutableContentModelBlockBase< + 'BlockGroup', + ContentModelListItemFormat, + HTMLLIElement + > { /** * Type of this list, either ordered or unordered */ diff --git a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelTableCell.ts b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelTableCell.ts index 4e51590c48b..03749696b78 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelTableCell.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/blockGroup/ContentModelTableCell.ts @@ -1,20 +1,29 @@ import type { TableCellMetadataFormat } from '../format/metadata/TableCellMetadataFormat'; -import type { ContentModelBlockGroupBase } from './ContentModelBlockGroupBase'; -import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; +import type { + ContentModelBlockGroupBase, + ReadonlyContentModelBlockGroupBase, + ShallowMutableContentModelBlockGroupBase, +} from './ContentModelBlockGroupBase'; import type { ContentModelTableCellFormat } from '../format/ContentModelTableCellFormat'; -import type { ContentModelWithDataset } from '../format/ContentModelWithDataset'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; -import type { Selectable } from '../common/Selectable'; +import type { + ContentModelWithDataset, + ReadonlyContentModelWithDataset, + ShallowMutableContentModelWithDataset, +} from '../format/ContentModelWithDataset'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; +import type { + ReadonlySelectable, + Selectable, + ShallowMutableSelectable, +} from '../common/Selectable'; /** - * Content Model of Table Cell + * Common part of Content Model of Table Cell */ -export interface ContentModelTableCell - extends Selectable, - ContentModelBlockGroupBase<'TableCell'>, - ContentModelWithFormat, - ContentModelWithDataset, - ContentModelBlockWithCache { +export interface ContentModelTableCellCommon { /** * Whether this cell is spanned from left cell */ @@ -30,3 +39,33 @@ export interface ContentModelTableCell */ isHeader?: boolean; } + +/** + * Content Model of Table Cell + */ +export interface ContentModelTableCell + extends Selectable, + ContentModelTableCellCommon, + ContentModelBlockGroupBase<'TableCell', HTMLTableCellElement>, + ContentModelWithFormat, + ContentModelWithDataset {} + +/** + * Content Model of Table Cell (Readonly) + */ +export interface ReadonlyContentModelTableCell + extends ReadonlySelectable, + Readonly, + ReadonlyContentModelBlockGroupBase<'TableCell', HTMLTableCellElement>, + ReadonlyContentModelWithFormat, + ReadonlyContentModelWithDataset {} + +/** + * Content Model of Table Cell (Shallow mutable) + */ +export interface ShallowMutableContentModelTableCell + extends ShallowMutableSelectable, + ContentModelTableCellCommon, + ShallowMutableContentModelBlockGroupBase<'TableCell', HTMLTableCellElement>, + ContentModelWithFormat, + ShallowMutableContentModelWithDataset {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/common/MutableMark.ts b/packages/roosterjs-content-model-types/lib/contentModel/common/MutableMark.ts new file mode 100644 index 00000000000..9912a147c44 --- /dev/null +++ b/packages/roosterjs-content-model-types/lib/contentModel/common/MutableMark.ts @@ -0,0 +1,73 @@ +// We are using a tag type to mark a content model type as mutable. + +// This is generally a workaround to https://github.com/microsoft/TypeScript/issues/13347 + +// In order to know if a block has been changed, we want to mark all blocks, blocks groups, segments and their members as readonly, +// When we want to change a block/segment/block group, we need to call a function to convert it to mutable. Inside this function +// we can make some change to the object (e.g. remove cached element if any) so later we know this object is changed. +// So that we expect there is a build time error if we assign a readonly object to a function that accepts mutable object only. +// However this does not happen today. + +// To workaround it, we manually add a hidden member (dummy) to all mutable types, and add another member with readonly array type to +// readonly types. When we assign readonly object to mutable one, compiler will fail to build since the two arrays are not matching. +// So that we can know where to fix from build time. And since the dummy value is optional, it won't break existing creator code. + +// @example +// let readonly: ReadonlyMark = {}; +// let mutable: MutableMark = {}; + +// readonly = mutable; // OK +// mutable = readonly; // Error: Type 'ReadonlyMark' is not assignable to type 'MutableMark'. + +/** + * Mark an object as mutable + */ +export type MutableMark = { + /** + * The mutable marker to mark an object as mutable. When assign readonly object to a mutable type, compile will fail to build + * due to this member does not exist from source type. + */ + readonly dummy1?: never[]; + + /** + * The mutable marker to mark an object as mutable. When assign readonly object to a mutable type, compile will fail to build + * due to this member does not exist from source type. + */ + readonly dummy2?: never[]; +}; + +/** + * Mark an object as single level mutable (child models are still readonly) + */ +export type ShallowMutableMark = { + /** + * The mutable marker to mark an object as mutable. When assign readonly object to a mutable type, compile will fail to build + * due to this member does not exist from source type. + */ + readonly dummy1?: never[]; + + /** + * The mutable marker to mark an object as mutable. When assign readonly object to a mutable type, compile will fail to build + * due to this member does not exist from source type. + * This is used for preventing assigning ShallowMutableMark to MutableMark + */ + readonly dummy2?: ReadonlyArray; +}; + +/** + * Mark an object as readonly + */ +export type ReadonlyMark = { + /** + * The mutable marker to mark an object as mutable. When assign readonly object to a mutable type, compile will fail to build + * due to this member does not exist from source type. + * This is used for preventing assigning ReadonlyMark to ShallowMutableMark or MutableMark + */ + readonly dummy1?: ReadonlyArray; + + /** + * The mutable marker to mark an object as mutable. When assign readonly object to a mutable type, compile will fail to build + * due to this member does not exist from source type. + */ + readonly dummy2?: ReadonlyArray; +}; diff --git a/packages/roosterjs-content-model-types/lib/contentModel/common/MutableType.ts b/packages/roosterjs-content-model-types/lib/contentModel/common/MutableType.ts new file mode 100644 index 00000000000..ecc921b98e6 --- /dev/null +++ b/packages/roosterjs-content-model-types/lib/contentModel/common/MutableType.ts @@ -0,0 +1,101 @@ +import type { ContentModelBr, ReadonlyContentModelBr } from '../segment/ContentModelBr'; +import type { ContentModelCode, ReadonlyContentModelCode } from '../decorator/ContentModelCode'; +import type { + ContentModelDivider, + ReadonlyContentModelDivider, +} from '../block/ContentModelDivider'; +import type { + ShallowMutableContentModelDocument, + ReadonlyContentModelDocument, +} from '../blockGroup/ContentModelDocument'; +import type { ContentModelEntity } from '../entity/ContentModelEntity'; +import type { + ShallowMutableContentModelFormatContainer, + ReadonlyContentModelFormatContainer, +} from '../blockGroup/ContentModelFormatContainer'; +import type { + ShallowMutableContentModelGeneralBlock, + ReadonlyContentModelGeneralBlock, +} from '../blockGroup/ContentModelGeneralBlock'; +import type { + ShallowMutableContentModelGeneralSegment, + ReadonlyContentModelGeneralSegment, +} from '../segment/ContentModelGeneralSegment'; +import type { ContentModelImage, ReadonlyContentModelImage } from '../segment/ContentModelImage'; +import type { ContentModelLink, ReadonlyContentModelLink } from '../decorator/ContentModelLink'; +import type { + ShallowMutableContentModelListItem, + ReadonlyContentModelListItem, +} from '../blockGroup/ContentModelListItem'; +import type { + ContentModelListLevel, + ReadonlyContentModelListLevel, +} from '../decorator/ContentModelListLevel'; +import type { + ReadonlyContentModelParagraph, + ShallowMutableContentModelParagraph, +} from '../block/ContentModelParagraph'; +import type { + ContentModelParagraphDecorator, + ReadonlyContentModelParagraphDecorator, +} from '../decorator/ContentModelParagraphDecorator'; +import type { + ContentModelSelectionMarker, + ReadonlyContentModelSelectionMarker, +} from '../segment/ContentModelSelectionMarker'; +import type { + ReadonlyContentModelTable, + ShallowMutableContentModelTable, +} from '../block/ContentModelTable'; +import type { + ShallowMutableContentModelTableCell, + ReadonlyContentModelTableCell, +} from '../blockGroup/ContentModelTableCell'; +import type { + ContentModelTableRow, + ReadonlyContentModelTableRow, +} from '../block/ContentModelTableRow'; +import type { ContentModelText, ReadonlyContentModelText } from '../segment/ContentModelText'; + +/** + * Get mutable type from its related readonly type + */ +export type MutableType = T extends ReadonlyContentModelGeneralSegment + ? ShallowMutableContentModelGeneralSegment + : T extends ReadonlyContentModelSelectionMarker + ? ContentModelSelectionMarker + : T extends ReadonlyContentModelImage + ? ContentModelImage + : T extends ContentModelEntity + ? ContentModelEntity + : T extends ReadonlyContentModelText + ? ContentModelText + : T extends ReadonlyContentModelBr + ? ContentModelBr + : T extends ReadonlyContentModelParagraph + ? ShallowMutableContentModelParagraph + : T extends ReadonlyContentModelTable + ? ShallowMutableContentModelTable + : T extends ReadonlyContentModelTableRow + ? ContentModelTableRow + : T extends ReadonlyContentModelTableCell + ? ShallowMutableContentModelTableCell + : T extends ReadonlyContentModelFormatContainer + ? ShallowMutableContentModelFormatContainer + : T extends ReadonlyContentModelListItem + ? ShallowMutableContentModelListItem + : T extends ReadonlyContentModelListLevel + ? ContentModelListLevel + : T extends ReadonlyContentModelDivider + ? ContentModelDivider + : T extends ReadonlyContentModelDocument + ? ShallowMutableContentModelDocument + : T extends ReadonlyContentModelGeneralBlock + ? ShallowMutableContentModelGeneralBlock + : T extends ReadonlyContentModelParagraphDecorator + ? ContentModelParagraphDecorator + : T extends ReadonlyContentModelLink + ? ContentModelLink + : T extends ReadonlyContentModelCode + ? ContentModelCode + : never; diff --git a/packages/roosterjs-content-model-types/lib/contentModel/common/Selectable.ts b/packages/roosterjs-content-model-types/lib/contentModel/common/Selectable.ts index 2e28a98e1e2..d9aa25b08e8 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/common/Selectable.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/common/Selectable.ts @@ -1,7 +1,29 @@ +import type { MutableMark, ReadonlyMark, ShallowMutableMark } from '../common/MutableMark'; + /** * Represents a selectable Content Model object */ -export interface Selectable { +export interface Selectable extends MutableMark { + /** + * Whether this model object is selected + */ + isSelected?: boolean; +} + +/** + * Represents a selectable Content Model object (Readonly) + */ +export interface ReadonlySelectable extends ReadonlyMark { + /** + * Whether this model object is selected + */ + readonly isSelected?: boolean; +} + +/** + * Represents a selectable Content Model object (Shallow mutable) + */ +export interface ShallowMutableSelectable extends ShallowMutableMark { /** * Whether this model object is selected */ diff --git a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelCode.ts b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelCode.ts index b124d0e61b5..d6823d9b496 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelCode.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelCode.ts @@ -1,9 +1,24 @@ +import type { MutableMark, ReadonlyMark } from '../common/MutableMark'; import type { ContentModelCodeFormat } from '../format/ContentModelCodeFormat'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; /** * Represent code info of Content Model. * ContentModelCode is a decorator but not a standalone model type, instead it need to be put inside a ContentModelSegment * since code is also a kind of segment, with some extra information */ -export interface ContentModelCode extends ContentModelWithFormat {} +export interface ContentModelCode + extends MutableMark, + ContentModelWithFormat {} + +/** + * Represent code info of Content Model. (Readonly) + * ContentModelCode is a decorator but not a standalone model type, instead it need to be put inside a ContentModelSegment + * since code is also a kind of segment, with some extra information + */ +export interface ReadonlyContentModelCode + extends ReadonlyMark, + ReadonlyContentModelWithFormat {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelDecorator.ts b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelDecorator.ts index b8fe53b3f2d..44e2a394627 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelDecorator.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelDecorator.ts @@ -1,8 +1,16 @@ -import type { ContentModelCode } from './ContentModelCode'; -import type { ContentModelLink } from './ContentModelLink'; -import type { ContentModelListLevel } from './ContentModelListLevel'; +import type { ContentModelCode, ReadonlyContentModelCode } from './ContentModelCode'; +import type { ContentModelLink, ReadonlyContentModelLink } from './ContentModelLink'; +import type { ContentModelListLevel, ReadonlyContentModelListLevel } from './ContentModelListLevel'; /** * Union type for segment decorators */ export type ContentModelDecorator = ContentModelLink | ContentModelCode | ContentModelListLevel; + +/** + * Union type for segment decorators (Readonly) + */ +export type ReadonlyContentModelDecorator = + | ReadonlyContentModelLink + | ReadonlyContentModelCode + | ReadonlyContentModelListLevel; diff --git a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelLink.ts b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelLink.ts index c0622fba7ef..4aa98459542 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelLink.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelLink.ts @@ -1,6 +1,13 @@ +import type { MutableMark, ReadonlyMark } from '../common/MutableMark'; import type { ContentModelHyperLinkFormat } from '../format/ContentModelHyperLinkFormat'; -import type { ContentModelWithDataset } from '../format/ContentModelWithDataset'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; +import type { + ContentModelWithDataset, + ReadonlyContentModelWithDataset, +} from '../format/ContentModelWithDataset'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; /** * Represent link info of Content Model. @@ -8,5 +15,16 @@ import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; * since link is also a kind of segment, with some extra information */ export interface ContentModelLink - extends ContentModelWithFormat, + extends MutableMark, + ContentModelWithFormat, ContentModelWithDataset {} + +/** + * Represent link info of Content Model (Readonly). + * ContentModelLink is not a standalone model type, instead it need to be put inside a ContentModelSegment + * since link is also a kind of segment, with some extra information + */ +export interface ReadonlyContentModelLink + extends ReadonlyMark, + ReadonlyContentModelWithFormat, + ReadonlyContentModelWithDataset {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelListLevel.ts b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelListLevel.ts index 206d541701e..585b0dce4ca 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelListLevel.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelListLevel.ts @@ -1,16 +1,42 @@ +import type { ContentModelBlockWithCache } from '../common/ContentModelBlockWithCache'; +import type { MutableMark, ReadonlyMark } from '../common/MutableMark'; import type { ContentModelListItemLevelFormat } from '../format/ContentModelListItemLevelFormat'; -import type { ContentModelWithDataset } from '../format/ContentModelWithDataset'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; +import type { + ContentModelWithDataset, + ReadonlyContentModelWithDataset, +} from '../format/ContentModelWithDataset'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; import type { ListMetadataFormat } from '../format/metadata/ListMetadataFormat'; /** - * Content Model of List Level + * Common part of Content Model of List Level */ -export interface ContentModelListLevel - extends ContentModelWithFormat, - ContentModelWithDataset { +export interface ContentModelListLevelCommon { /** * Type of a list, order (OL) or unordered (UL) */ listType: 'OL' | 'UL'; } + +/** + * Content Model of List Level + */ +export interface ContentModelListLevel + extends MutableMark, + ContentModelBlockWithCache, + ContentModelListLevelCommon, + ContentModelWithFormat, + ContentModelWithDataset {} + +/** + * Content Model of List Level (Readonly) + */ +export interface ReadonlyContentModelListLevel + extends ReadonlyMark, + ContentModelBlockWithCache, + ReadonlyContentModelWithFormat, + ReadonlyContentModelWithDataset, + Readonly {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelParagraphDecorator.ts b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelParagraphDecorator.ts index b3c154b6ff1..7eeebcc19b4 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelParagraphDecorator.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/decorator/ContentModelParagraphDecorator.ts @@ -1,15 +1,36 @@ +import type { MutableMark, ReadonlyMark } from '../common/MutableMark'; import type { ContentModelSegmentFormat } from '../format/ContentModelSegmentFormat'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; /** - * Represent decorator for a paragraph in Content Model - * A decorator of paragraph can represent a heading, or a P tag that act likes a paragraph but with some extra format info - * since heading is also a kind of paragraph, with some extra information + * Common part of decorator for a paragraph in Content Model */ -export interface ContentModelParagraphDecorator - extends ContentModelWithFormat { +export interface ContentModelParagraphDecoratorCommon { /** * Tag name of this paragraph */ tagName: string; } + +/** + * Represent decorator for a paragraph in Content Model + * A decorator of paragraph can represent a heading, or a P tag that act likes a paragraph but with some extra format info + * since heading is also a kind of paragraph, with some extra information + */ +export interface ContentModelParagraphDecorator + extends MutableMark, + ContentModelParagraphDecoratorCommon, + ContentModelWithFormat {} + +/** + * Represent decorator for a paragraph in Content Model (Readonly) + * A decorator of paragraph can represent a heading, or a P tag that act likes a paragraph but with some extra format info + * since heading is also a kind of paragraph, with some extra information + */ +export interface ReadonlyContentModelParagraphDecorator + extends ReadonlyMark, + ReadonlyContentModelWithFormat, + Readonly {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/format/ContentModelWithDataset.ts b/packages/roosterjs-content-model-types/lib/contentModel/format/ContentModelWithDataset.ts index 0fe8f417c78..902f4dd2d5e 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/format/ContentModelWithDataset.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/format/ContentModelWithDataset.ts @@ -1,11 +1,32 @@ -import type { DatasetFormat } from './metadata/DatasetFormat'; +import type { MutableMark, ReadonlyMark, ShallowMutableMark } from '../common/MutableMark'; +import type { DatasetFormat, ReadonlyDatasetFormat } from './metadata/DatasetFormat'; /** * Represents base format of an element that supports dataset and/or metadata */ -export interface ContentModelWithDataset { +export type ContentModelWithDataset = MutableMark & { /** * dataset of this element */ dataset: DatasetFormat; -} +}; + +/** + * Represents base format of an element that supports dataset and/or metadata (Readonly) + */ +export type ReadonlyContentModelWithDataset = ReadonlyMark & { + /** + * dataset of this element + */ + readonly dataset: ReadonlyDatasetFormat; +}; + +/** + * Represents base format of an element that supports dataset and/or metadata (Readonly) + */ +export type ShallowMutableContentModelWithDataset = ShallowMutableMark & { + /** + * dataset of this element + */ + dataset: DatasetFormat; +}; diff --git a/packages/roosterjs-content-model-types/lib/contentModel/format/ContentModelWithFormat.ts b/packages/roosterjs-content-model-types/lib/contentModel/format/ContentModelWithFormat.ts index 53f52e67522..cfbe0d6b821 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/format/ContentModelWithFormat.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/format/ContentModelWithFormat.ts @@ -9,3 +9,13 @@ export interface ContentModelWithFormat { */ format: T; } + +/** + * Represent a content model with format (Readonly) + */ +export interface ReadonlyContentModelWithFormat { + /** + * Format of this model + */ + readonly format: Readonly; +} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/format/metadata/DatasetFormat.ts b/packages/roosterjs-content-model-types/lib/contentModel/format/metadata/DatasetFormat.ts index e71cadf3c37..11625671ba6 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/format/metadata/DatasetFormat.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/format/metadata/DatasetFormat.ts @@ -2,3 +2,8 @@ * Represents dataset format of Content Model */ export type DatasetFormat = Record; + +/** + * Represents dataset format of Content Model (Readonly) + */ +export type ReadonlyDatasetFormat = Readonly>; diff --git a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelBr.ts b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelBr.ts index d8bf1b04871..e414626c817 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelBr.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelBr.ts @@ -1,6 +1,14 @@ -import type { ContentModelSegmentBase } from './ContentModelSegmentBase'; +import type { + ContentModelSegmentBase, + ReadonlyContentModelSegmentBase, +} from './ContentModelSegmentBase'; /** * Content Model of BR */ export interface ContentModelBr extends ContentModelSegmentBase<'Br'> {} + +/** + * Content Model of BR (Readonly) + */ +export interface ReadonlyContentModelBr extends ReadonlyContentModelSegmentBase<'Br'> {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelGeneralSegment.ts b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelGeneralSegment.ts index bbd0741c7ac..3bfded832e0 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelGeneralSegment.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelGeneralSegment.ts @@ -1,6 +1,14 @@ import type { ContentModelBlockFormat } from '../format/ContentModelBlockFormat'; -import type { ContentModelGeneralBlock } from '../blockGroup/ContentModelGeneralBlock'; -import type { ContentModelSegmentBase } from './ContentModelSegmentBase'; +import type { + ContentModelGeneralBlock, + ReadonlyContentModelGeneralBlock, + ShallowMutableContentModelGeneralBlock, +} from '../blockGroup/ContentModelGeneralBlock'; +import type { + ContentModelSegmentBase, + ReadonlyContentModelSegmentBase, + ShallowMutableContentModelSegmentBase, +} from './ContentModelSegmentBase'; import type { ContentModelSegmentFormat } from '../format/ContentModelSegmentFormat'; /** @@ -9,3 +17,23 @@ import type { ContentModelSegmentFormat } from '../format/ContentModelSegmentFor export interface ContentModelGeneralSegment extends ContentModelGeneralBlock, ContentModelSegmentBase<'General', ContentModelBlockFormat & ContentModelSegmentFormat> {} + +/** + * Content Model of general Segment (Readonly) + */ +export interface ReadonlyContentModelGeneralSegment + extends ReadonlyContentModelGeneralBlock, + ReadonlyContentModelSegmentBase< + 'General', + ContentModelBlockFormat & ContentModelSegmentFormat + > {} + +/** + * Content Model of general Segment (Shallow mutable) + */ +export interface ShallowMutableContentModelGeneralSegment + extends ShallowMutableContentModelGeneralBlock, + ShallowMutableContentModelSegmentBase< + 'General', + ContentModelBlockFormat & ContentModelSegmentFormat + > {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelImage.ts b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelImage.ts index 8b457ce4f0c..9b7e531d728 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelImage.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelImage.ts @@ -1,14 +1,18 @@ import type { ContentModelImageFormat } from '../format/ContentModelImageFormat'; -import type { ContentModelSegmentBase } from './ContentModelSegmentBase'; -import type { ContentModelWithDataset } from '../format/ContentModelWithDataset'; +import type { + ContentModelSegmentBase, + ReadonlyContentModelSegmentBase, +} from './ContentModelSegmentBase'; +import type { + ContentModelWithDataset, + ReadonlyContentModelWithDataset, +} from '../format/ContentModelWithDataset'; import type { ImageMetadataFormat } from '../format/metadata/ImageMetadataFormat'; /** - * Content Model of IMG + * Common part of Content Model of IMG */ -export interface ContentModelImage - extends ContentModelSegmentBase<'Image', ContentModelImageFormat>, - ContentModelWithDataset { +export interface ContentModelImageCommon { /** * Image source of this IMG element */ @@ -29,3 +33,19 @@ export interface ContentModelImage */ isSelectedAsImageSelection?: boolean; } + +/** + * Content Model of IMG + */ +export interface ContentModelImage + extends ContentModelImageCommon, + ContentModelSegmentBase<'Image', ContentModelImageFormat>, + ContentModelWithDataset {} + +/** + * Content Model of IMG (Readonly) + */ +export interface ReadonlyContentModelImage + extends ReadonlyContentModelSegmentBase<'Image', ContentModelImageFormat>, + ReadonlyContentModelWithDataset, + Readonly {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSegment.ts b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSegment.ts index 77fd2c68cad..4989fddc1c4 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSegment.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSegment.ts @@ -1,9 +1,16 @@ -import type { ContentModelBr } from './ContentModelBr'; +import type { ContentModelBr, ReadonlyContentModelBr } from './ContentModelBr'; import type { ContentModelEntity } from '../entity/ContentModelEntity'; -import type { ContentModelGeneralSegment } from './ContentModelGeneralSegment'; -import type { ContentModelImage } from './ContentModelImage'; -import type { ContentModelSelectionMarker } from './ContentModelSelectionMarker'; -import type { ContentModelText } from './ContentModelText'; +import type { + ContentModelGeneralSegment, + ReadonlyContentModelGeneralSegment, + ShallowMutableContentModelGeneralSegment, +} from './ContentModelGeneralSegment'; +import type { ContentModelImage, ReadonlyContentModelImage } from './ContentModelImage'; +import type { + ContentModelSelectionMarker, + ReadonlyContentModelSelectionMarker, +} from './ContentModelSelectionMarker'; +import type { ContentModelText, ReadonlyContentModelText } from './ContentModelText'; /** * Union type of Content Model Segment @@ -15,3 +22,25 @@ export type ContentModelSegment = | ContentModelGeneralSegment | ContentModelEntity | ContentModelImage; + +/** + * Union type of Content Model Segment (Readonly) + */ +export type ReadonlyContentModelSegment = + | ReadonlyContentModelSelectionMarker + | ReadonlyContentModelText + | ReadonlyContentModelBr + | ReadonlyContentModelGeneralSegment + | ContentModelEntity + | ReadonlyContentModelImage; + +/** + * Union type of Content Model Segment (Shallow mutable) + */ +export type ShallowMutableContentModelSegment = + | ContentModelSelectionMarker + | ContentModelText + | ContentModelBr + | ShallowMutableContentModelGeneralSegment + | ContentModelEntity + | ContentModelImage; diff --git a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSegmentBase.ts b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSegmentBase.ts index 22df2695372..5f169c3eac7 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSegmentBase.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSegmentBase.ts @@ -1,9 +1,27 @@ -import type { ContentModelCode } from '../decorator/ContentModelCode'; -import type { ContentModelLink } from '../decorator/ContentModelLink'; +import type { MutableMark, ReadonlyMark, ShallowMutableMark } from '../common/MutableMark'; +import type { ContentModelCode, ReadonlyContentModelCode } from '../decorator/ContentModelCode'; +import type { ContentModelLink, ReadonlyContentModelLink } from '../decorator/ContentModelLink'; import type { ContentModelSegmentFormat } from '../format/ContentModelSegmentFormat'; import type { ContentModelSegmentType } from './SegmentType'; -import type { ContentModelWithFormat } from '../format/ContentModelWithFormat'; -import type { Selectable } from '../common/Selectable'; +import type { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from '../format/ContentModelWithFormat'; +import type { + ReadonlySelectable, + Selectable, + ShallowMutableSelectable, +} from '../common/Selectable'; + +/** + * Common part of base type of Content Model Segment + */ +export interface ContentModelSegmentBaseCommon { + /** + * Type of this segment + */ + readonly segmentType: T; +} /** * Base type of Content Model Segment @@ -11,12 +29,55 @@ import type { Selectable } from '../common/Selectable'; export interface ContentModelSegmentBase< T extends ContentModelSegmentType, TFormat extends ContentModelSegmentFormat = ContentModelSegmentFormat -> extends Selectable, ContentModelWithFormat { +> + extends MutableMark, + Selectable, + ContentModelWithFormat, + ContentModelSegmentBaseCommon { /** - * Type of this segment + * Hyperlink info */ - segmentType: T; + link?: ContentModelLink; + + /** + * Code info + */ + code?: ContentModelCode; +} +/** + * Base type of Content Model Segment (Readonly) + */ +export interface ReadonlyContentModelSegmentBase< + T extends ContentModelSegmentType, + TFormat extends ContentModelSegmentFormat = ContentModelSegmentFormat +> + extends ReadonlyMark, + ReadonlySelectable, + ReadonlyContentModelWithFormat, + Readonly> { + /** + * Hyperlink info + */ + readonly link?: ReadonlyContentModelLink; + + /** + * Code info + */ + readonly code?: ReadonlyContentModelCode; +} + +/** + * Base type of Content Model Segment (Shallow mutable) + */ +export interface ShallowMutableContentModelSegmentBase< + T extends ContentModelSegmentType, + TFormat extends ContentModelSegmentFormat = ContentModelSegmentFormat +> + extends ShallowMutableMark, + ShallowMutableSelectable, + ContentModelWithFormat, + ContentModelSegmentBaseCommon { /** * Hyperlink info */ diff --git a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSelectionMarker.ts b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSelectionMarker.ts index e99db906635..2e1f9b400eb 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSelectionMarker.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelSelectionMarker.ts @@ -1,6 +1,15 @@ -import type { ContentModelSegmentBase } from './ContentModelSegmentBase'; +import type { + ContentModelSegmentBase, + ReadonlyContentModelSegmentBase, +} from './ContentModelSegmentBase'; /** * Content Model of Selection Marker */ export interface ContentModelSelectionMarker extends ContentModelSegmentBase<'SelectionMarker'> {} + +/** + * Content Model of Selection Marker (Readonly) + */ +export interface ReadonlyContentModelSelectionMarker + extends ReadonlyContentModelSegmentBase<'SelectionMarker'> {} diff --git a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelText.ts b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelText.ts index 5cd7c79f19b..7cee676ad6c 100644 --- a/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelText.ts +++ b/packages/roosterjs-content-model-types/lib/contentModel/segment/ContentModelText.ts @@ -1,11 +1,26 @@ -import type { ContentModelSegmentBase } from './ContentModelSegmentBase'; +import type { + ContentModelSegmentBase, + ReadonlyContentModelSegmentBase, +} from './ContentModelSegmentBase'; /** - * Content Model for Text + * Common port of Content Model for Text */ -export interface ContentModelText extends ContentModelSegmentBase<'Text'> { +export interface ContentModelTextCommon { /** * Text content of this segment */ text: string; } + +/** + * Content Model for Text + */ +export interface ContentModelText extends ContentModelTextCommon, ContentModelSegmentBase<'Text'> {} + +/** + * Content Model for Text (Readonly) + */ +export interface ReadonlyContentModelText + extends ReadonlyContentModelSegmentBase<'Text'>, + Readonly {} diff --git a/packages/roosterjs-content-model-types/lib/index.ts b/packages/roosterjs-content-model-types/lib/index.ts index a6b748c4c68..9f696e2c23b 100644 --- a/packages/roosterjs-content-model-types/lib/index.ts +++ b/packages/roosterjs-content-model-types/lib/index.ts @@ -1,7 +1,14 @@ export { ContentModelSegmentFormat } from './contentModel/format/ContentModelSegmentFormat'; -export { ContentModelWithFormat } from './contentModel/format/ContentModelWithFormat'; +export { + ContentModelWithFormat, + ReadonlyContentModelWithFormat, +} from './contentModel/format/ContentModelWithFormat'; export { ContentModelTableFormat } from './contentModel/format/ContentModelTableFormat'; -export { ContentModelWithDataset } from './contentModel/format/ContentModelWithDataset'; +export { + ContentModelWithDataset, + ReadonlyContentModelWithDataset, + ShallowMutableContentModelWithDataset, +} from './contentModel/format/ContentModelWithDataset'; export { ContentModelBlockFormat } from './contentModel/format/ContentModelBlockFormat'; export { ContentModelTableCellFormat } from './contentModel/format/ContentModelTableCellFormat'; export { ContentModelListItemFormat } from './contentModel/format/ContentModelListItemFormat'; @@ -50,7 +57,7 @@ export { ListStyleFormat } from './contentModel/format/formatParts/ListStyleForm export { FloatFormat } from './contentModel/format/formatParts/FloatFormat'; export { EntityInfoFormat } from './contentModel/format/formatParts/EntityInfoFormat'; -export { DatasetFormat } from './contentModel/format/metadata/DatasetFormat'; +export { DatasetFormat, ReadonlyDatasetFormat } from './contentModel/format/metadata/DatasetFormat'; export { TableMetadataFormat } from './contentModel/format/metadata/TableMetadataFormat'; export { ListMetadataFormat } from './contentModel/format/metadata/ListMetadataFormat'; export { @@ -89,39 +96,147 @@ export { DeleteResult } from './enum/DeleteResult'; export { InsertEntityPosition } from './enum/InsertEntityPosition'; export { ExportContentMode } from './enum/ExportContentMode'; -export { ContentModelBlock } from './contentModel/block/ContentModelBlock'; -export { ContentModelParagraph } from './contentModel/block/ContentModelParagraph'; -export { ContentModelTable } from './contentModel/block/ContentModelTable'; -export { ContentModelDivider } from './contentModel/block/ContentModelDivider'; -export { ContentModelBlockBase } from './contentModel/block/ContentModelBlockBase'; +export { + ContentModelBlock, + ReadonlyContentModelBlock, + ShallowMutableContentModelBlock, +} from './contentModel/block/ContentModelBlock'; +export { + ContentModelParagraph, + ContentModelParagraphCommon, + ReadonlyContentModelParagraph, + ShallowMutableContentModelParagraph, +} from './contentModel/block/ContentModelParagraph'; +export { + ContentModelTable, + ReadonlyContentModelTable, + ShallowMutableContentModelTable, +} from './contentModel/block/ContentModelTable'; +export { + ContentModelDivider, + ContentModelDividerCommon, + ReadonlyContentModelDivider, +} from './contentModel/block/ContentModelDivider'; +export { + ContentModelBlockBase, + ContentModelBlockBaseCommon, + ReadonlyContentModelBlockBase, + ShallowMutableContentModelBlockBase, +} from './contentModel/block/ContentModelBlockBase'; export { ContentModelBlockWithCache } from './contentModel/common/ContentModelBlockWithCache'; -export { ContentModelTableRow } from './contentModel/block/ContentModelTableRow'; +export { + ContentModelTableRow, + ContentModelTableRowCommon, + ReadonlyContentModelTableRow, + ShallowMutableContentModelTableRow, +} from './contentModel/block/ContentModelTableRow'; export { ContentModelEntity } from './contentModel/entity/ContentModelEntity'; -export { ContentModelDocument } from './contentModel/blockGroup/ContentModelDocument'; -export { ContentModelBlockGroupBase } from './contentModel/blockGroup/ContentModelBlockGroupBase'; -export { ContentModelFormatContainer } from './contentModel/blockGroup/ContentModelFormatContainer'; -export { ContentModelGeneralBlock } from './contentModel/blockGroup/ContentModelGeneralBlock'; -export { ContentModelListItem } from './contentModel/blockGroup/ContentModelListItem'; -export { ContentModelTableCell } from './contentModel/blockGroup/ContentModelTableCell'; -export { ContentModelBlockGroup } from './contentModel/blockGroup/ContentModelBlockGroup'; +export { + ContentModelDocument, + ContentModelDocumentCommon, + ReadonlyContentModelDocument, + ShallowMutableContentModelDocument, +} from './contentModel/blockGroup/ContentModelDocument'; +export { + ContentModelBlockGroupBase, + ContentModelBlockGroupBaseCommon, + ReadonlyContentModelBlockGroupBase, + ShallowMutableContentModelBlockGroupBase, +} from './contentModel/blockGroup/ContentModelBlockGroupBase'; +export { + ContentModelFormatContainer, + ContentModelFormatContainerCommon, + ReadonlyContentModelFormatContainer, + ShallowMutableContentModelFormatContainer, +} from './contentModel/blockGroup/ContentModelFormatContainer'; +export { + ContentModelGeneralBlock, + ContentModelGeneralBlockCommon, + ReadonlyContentModelGeneralBlock, + ShallowMutableContentModelGeneralBlock, +} from './contentModel/blockGroup/ContentModelGeneralBlock'; +export { + ContentModelListItem, + ReadonlyContentModelListItem, + ShallowMutableContentModelListItem, +} from './contentModel/blockGroup/ContentModelListItem'; +export { + ContentModelTableCell, + ContentModelTableCellCommon, + ReadonlyContentModelTableCell, + ShallowMutableContentModelTableCell, +} from './contentModel/blockGroup/ContentModelTableCell'; +export { + ContentModelBlockGroup, + ReadonlyContentModelBlockGroup, + ShallowMutableContentModelBlockGroup, +} from './contentModel/blockGroup/ContentModelBlockGroup'; + +export { ContentModelBr, ReadonlyContentModelBr } from './contentModel/segment/ContentModelBr'; +export { + ContentModelGeneralSegment, + ReadonlyContentModelGeneralSegment, + ShallowMutableContentModelGeneralSegment, +} from './contentModel/segment/ContentModelGeneralSegment'; +export { + ContentModelImage, + ContentModelImageCommon, + ReadonlyContentModelImage, +} from './contentModel/segment/ContentModelImage'; +export { + ContentModelText, + ContentModelTextCommon, + ReadonlyContentModelText, +} from './contentModel/segment/ContentModelText'; +export { + ContentModelSelectionMarker, + ReadonlyContentModelSelectionMarker, +} from './contentModel/segment/ContentModelSelectionMarker'; +export { + ContentModelSegmentBase, + ContentModelSegmentBaseCommon, + ReadonlyContentModelSegmentBase, + ShallowMutableContentModelSegmentBase, +} from './contentModel/segment/ContentModelSegmentBase'; +export { + ContentModelSegment, + ReadonlyContentModelSegment, + ShallowMutableContentModelSegment, +} from './contentModel/segment/ContentModelSegment'; -export { ContentModelBr } from './contentModel/segment/ContentModelBr'; -export { ContentModelGeneralSegment } from './contentModel/segment/ContentModelGeneralSegment'; -export { ContentModelImage } from './contentModel/segment/ContentModelImage'; -export { ContentModelText } from './contentModel/segment/ContentModelText'; -export { ContentModelSelectionMarker } from './contentModel/segment/ContentModelSelectionMarker'; -export { ContentModelSegmentBase } from './contentModel/segment/ContentModelSegmentBase'; -export { ContentModelSegment } from './contentModel/segment/ContentModelSegment'; +export { + ContentModelCode, + ReadonlyContentModelCode, +} from './contentModel/decorator/ContentModelCode'; +export { + ContentModelLink, + ReadonlyContentModelLink, +} from './contentModel/decorator/ContentModelLink'; +export { + ContentModelParagraphDecorator, + ContentModelParagraphDecoratorCommon, + ReadonlyContentModelParagraphDecorator, +} from './contentModel/decorator/ContentModelParagraphDecorator'; +export { + ContentModelDecorator, + ReadonlyContentModelDecorator, +} from './contentModel/decorator/ContentModelDecorator'; +export { + ContentModelListLevel, + ContentModelListLevelCommon, + ReadonlyContentModelListLevel, +} from './contentModel/decorator/ContentModelListLevel'; -export { ContentModelCode } from './contentModel/decorator/ContentModelCode'; -export { ContentModelLink } from './contentModel/decorator/ContentModelLink'; -export { ContentModelParagraphDecorator } from './contentModel/decorator/ContentModelParagraphDecorator'; -export { ContentModelDecorator } from './contentModel/decorator/ContentModelDecorator'; -export { ContentModelListLevel } from './contentModel/decorator/ContentModelListLevel'; +export { + Selectable, + ReadonlySelectable, + ShallowMutableSelectable, +} from './contentModel/common/Selectable'; +export { MutableMark, ShallowMutableMark, ReadonlyMark } from './contentModel/common/MutableMark'; +export { MutableType } from './contentModel/common/MutableType'; -export { Selectable } from './contentModel/common/Selectable'; export { DOMSelection, SelectionType, From 926c2d1cf8dd40a329ec37da5eabc4da61aac828 Mon Sep 17 00:00:00 2001 From: "Julia Roldi (from Dev Box)" Date: Tue, 21 May 2024 13:06:04 -0300 Subject: [PATCH 2/7] test --- .../lib/autoFormat/AutoFormatPlugin.ts | 8 ++++++-- .../lib/autoFormat/link/createLink.ts | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts b/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts index b0936bdf511..f2f23aa5672 100644 --- a/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts +++ b/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts @@ -220,10 +220,14 @@ export class AutoFormatPlugin implements EditorPlugin { shouldFraction || shouldOrdinals ); - }, - formatOptions + } ); + editor.triggerEvent('contentChanged', { + source: formatOptions.changeSource ?? ChangeSource.Format, + formatApiName: formatOptions.apiName, + }); + break; } } diff --git a/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts b/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts index 7d997c765fc..2b220aa8567 100644 --- a/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts +++ b/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts @@ -9,6 +9,9 @@ export function createLink(editor: IEditor) { formatTextSegmentBeforeSelectionMarker( editor, (_model, linkSegment, _paragraph) => { + if (linkSegment.link) { + return true; + } let linkData: LinkData | null = null; if (!linkSegment.link && (linkData = matchLink(linkSegment.text))) { addLink(linkSegment, { @@ -20,6 +23,7 @@ export function createLink(editor: IEditor) { }); return true; } + return false; }, { From 1d8d743d68cec14aaf3d198503cb9ed783fab572 Mon Sep 17 00:00:00 2001 From: "Julia Roldi (from Dev Box)" Date: Tue, 21 May 2024 13:54:49 -0300 Subject: [PATCH 3/7] test --- .../lib/autoFormat/AutoFormatPlugin.ts | 2 +- .../lib/autoFormat/link/createLink.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts b/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts index f2f23aa5672..0d16944a3c4 100644 --- a/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts +++ b/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts @@ -249,7 +249,7 @@ export class AutoFormatPlugin implements EditorPlugin { private handleContentChangedEvent(editor: IEditor, event: ContentChangedEvent) { const { autoLink } = this.options; if (event.source == 'Paste' && autoLink) { - createLink(editor); + createLink(editor, event); } } } diff --git a/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts b/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts index 2b220aa8567..94b941fa29c 100644 --- a/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts +++ b/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts @@ -1,11 +1,11 @@ import { addLink, ChangeSource } from 'roosterjs-content-model-dom'; import { formatTextSegmentBeforeSelectionMarker, matchLink } from 'roosterjs-content-model-api'; -import type { IEditor, LinkData } from 'roosterjs-content-model-types'; +import type { ContentChangedEvent, IEditor, LinkData } from 'roosterjs-content-model-types'; /** * @internal */ -export function createLink(editor: IEditor) { +export function createLink(editor: IEditor, event: ContentChangedEvent) { formatTextSegmentBeforeSelectionMarker( editor, (_model, linkSegment, _paragraph) => { @@ -28,6 +28,9 @@ export function createLink(editor: IEditor) { }, { changeSource: ChangeSource.AutoLink, + getChangeData: () => { + return event.data; + }, } ); } From 11b943e26268754f912a79a2b4c9f010f99f03fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BAlia=20Roldi?= Date: Tue, 21 May 2024 16:31:04 -0300 Subject: [PATCH 4/7] link preview --- .../lib/autoFormat/link/createLink.ts | 12 ++++++++---- .../test/autoFormat/link/createLinkTest.ts | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts b/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts index 94b941fa29c..21efd02a57a 100644 --- a/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts +++ b/packages/roosterjs-content-model-plugins/lib/autoFormat/link/createLink.ts @@ -1,11 +1,12 @@ import { addLink, ChangeSource } from 'roosterjs-content-model-dom'; import { formatTextSegmentBeforeSelectionMarker, matchLink } from 'roosterjs-content-model-api'; -import type { ContentChangedEvent, IEditor, LinkData } from 'roosterjs-content-model-types'; +import type { IEditor, LinkData } from 'roosterjs-content-model-types'; /** * @internal */ -export function createLink(editor: IEditor, event: ContentChangedEvent) { +export function createLink(editor: IEditor) { + let anchorNode: Node | null = null; formatTextSegmentBeforeSelectionMarker( editor, (_model, linkSegment, _paragraph) => { @@ -28,9 +29,12 @@ export function createLink(editor: IEditor, event: ContentChangedEvent) { }, { changeSource: ChangeSource.AutoLink, - getChangeData: () => { - return event.data; + onNodeCreated: (_modelElement, node) => { + if (!anchorNode) { + anchorNode = node; + } }, + getChangeData: () => anchorNode, } ); } diff --git a/packages/roosterjs-content-model-plugins/test/autoFormat/link/createLinkTest.ts b/packages/roosterjs-content-model-plugins/test/autoFormat/link/createLinkTest.ts index e3496c40d77..edd4e5e7e31 100644 --- a/packages/roosterjs-content-model-plugins/test/autoFormat/link/createLinkTest.ts +++ b/packages/roosterjs-content-model-plugins/test/autoFormat/link/createLinkTest.ts @@ -163,6 +163,6 @@ describe('createLink', () => { format: {}, }; - runTest(input, input, false); + runTest(input, input, true); }); }); From 49958183477db99fd2c52f9f63cf11f4a5b92d4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BAlia=20Roldi?= Date: Tue, 21 May 2024 16:38:23 -0300 Subject: [PATCH 5/7] remove auto format plugin code --- .../lib/autoFormat/AutoFormatPlugin.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts b/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts index 0d16944a3c4..b0936bdf511 100644 --- a/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts +++ b/packages/roosterjs-content-model-plugins/lib/autoFormat/AutoFormatPlugin.ts @@ -220,14 +220,10 @@ export class AutoFormatPlugin implements EditorPlugin { shouldFraction || shouldOrdinals ); - } + }, + formatOptions ); - editor.triggerEvent('contentChanged', { - source: formatOptions.changeSource ?? ChangeSource.Format, - formatApiName: formatOptions.apiName, - }); - break; } } @@ -249,7 +245,7 @@ export class AutoFormatPlugin implements EditorPlugin { private handleContentChangedEvent(editor: IEditor, event: ContentChangedEvent) { const { autoLink } = this.options; if (event.source == 'Paste' && autoLink) { - createLink(editor, event); + createLink(editor); } } } From 1e128eafe698596505c84cb103eb141c137d540c Mon Sep 17 00:00:00 2001 From: Jiuqing Song Date: Tue, 21 May 2024 14:46:59 -0700 Subject: [PATCH 6/7] Content Model Cache improvement - Step 2: Prepare utility functions (#2641) * Readonly types (3rd try * Improve * fix build * Improve * improve * Improve * Add shallow mutable type * improve * Improve * improve * improve * add test * Readonly types step 2 * add test * Improve * improve * improve * improve * Improve * fix test * improve --- .../contentModel/ContentModelPanePlugin.ts | 6 +- .../components/format/MetadataView.tsx | 10 +- .../list/findListItemsInSameThread.ts | 43 ++- .../createContentModelTest.ts | 5 +- .../test/editor/EditorTest.ts | 4 +- .../roosterjs-content-model-dom/lib/index.ts | 17 +- .../lib/modelApi/common/addBlock.ts | 7 +- .../lib/modelApi/common/addSegment.ts | 25 +- .../lib/modelApi/common/ensureParagraph.ts | 25 +- .../lib/modelApi/editing/cloneModel.ts | 70 +++-- .../getClosestAncestorBlockGroupIndex.ts | 3 +- .../modelApi/metadata/updateImageMetadata.ts | 16 +- .../modelApi/metadata/updateListMetadata.ts | 17 +- .../lib/modelApi/metadata/updateMetadata.ts | 41 ++- .../metadata/updateTableCellMetadata.ts | 20 +- .../modelApi/metadata/updateTableMetadata.ts | 18 +- .../modelApi/selection/collectSelections.ts | 272 ++++++++++++++++-- .../modelApi/selection/iterateSelections.ts | 43 ++- .../modelApi/typeCheck/isBlockGroupOfType.ts | 25 ++ .../modelApi/typeCheck/isGeneralSegment.ts | 24 ++ .../editing/retrieveModelFormatStateTest.ts | 44 +-- .../metadata/updateImageMetadataTest.ts | 72 ++++- .../metadata/updateListMetadataTest.ts | 45 ++- .../modelApi/metadata/updateMetadataTest.ts | 95 +++++- .../metadata/updateTableCellMetadataTest.ts | 58 +++- .../metadata/updateTableMetadataTest.ts | 77 ++++- .../selection/collectSelectionsTest.ts | 5 +- .../selection/getSelectedSegmentsTest.ts | 36 ++- .../selection/iterateSelectionsTest.ts | 8 +- .../lib/index.ts | 8 +- .../lib/parameter/IterateSelectionsOption.ts | 35 ++- .../lib/parameter/OperationalBlocks.ts | 30 +- .../lib/parameter/TypeOfBlockGroup.ts | 16 +- .../lib/selection/TableSelectionContext.ts | 30 +- 34 files changed, 1090 insertions(+), 160 deletions(-) diff --git a/demo/scripts/controlsV2/sidePane/contentModel/ContentModelPanePlugin.ts b/demo/scripts/controlsV2/sidePane/contentModel/ContentModelPanePlugin.ts index 4bb8825a43a..1f2651ae146 100644 --- a/demo/scripts/controlsV2/sidePane/contentModel/ContentModelPanePlugin.ts +++ b/demo/scripts/controlsV2/sidePane/contentModel/ContentModelPanePlugin.ts @@ -1,3 +1,4 @@ +import { cloneModel } from 'roosterjs-content-model-dom'; import { ContentModelPane, ContentModelPaneProps } from './ContentModelPane'; import { createRibbonPlugin, RibbonButton, RibbonPlugin } from '../../roosterjsReact/ribbon'; import { getRefreshButton } from './buttons/refreshButton'; @@ -70,8 +71,9 @@ export class ContentModelPanePlugin extends SidePanePluginImpl< this.getComponent(component => { this.editor.formatContentModel( model => { - component.setContentModel(model); - setCurrentContentModel(model); + const clonedModel = cloneModel(model); + component.setContentModel(clonedModel); + setCurrentContentModel(clonedModel); return false; }, diff --git a/demo/scripts/controlsV2/sidePane/contentModel/components/format/MetadataView.tsx b/demo/scripts/controlsV2/sidePane/contentModel/components/format/MetadataView.tsx index 40618e31f1c..493f20902f9 100644 --- a/demo/scripts/controlsV2/sidePane/contentModel/components/format/MetadataView.tsx +++ b/demo/scripts/controlsV2/sidePane/contentModel/components/format/MetadataView.tsx @@ -1,13 +1,19 @@ import * as React from 'react'; -import { ContentModelWithDataset } from 'roosterjs-content-model-types'; import { FormatRenderer } from './utils/FormatRenderer'; +import { + ContentModelWithDataset, + ShallowMutableContentModelWithDataset, +} from 'roosterjs-content-model-types'; const styles = require('./FormatView.scss'); export function MetadataView(props: { model: ContentModelWithDataset; renderers: FormatRenderer[]; - updater: (model: ContentModelWithDataset, callback: (format: T | null) => T | null) => void; + updater: ( + model: ShallowMutableContentModelWithDataset, + callback: (format: T | null) => T | null + ) => void; }) { const { model, renderers, updater } = props; const metadata = React.useRef(null); diff --git a/packages/roosterjs-content-model-api/lib/modelApi/list/findListItemsInSameThread.ts b/packages/roosterjs-content-model-api/lib/modelApi/list/findListItemsInSameThread.ts index 3ad7824f584..14b9f4ff99f 100644 --- a/packages/roosterjs-content-model-api/lib/modelApi/list/findListItemsInSameThread.ts +++ b/packages/roosterjs-content-model-api/lib/modelApi/list/findListItemsInSameThread.ts @@ -1,14 +1,34 @@ -import type { ContentModelBlockGroup, ContentModelListItem } from 'roosterjs-content-model-types'; +import type { + ContentModelBlockGroup, + ContentModelListItem, + ReadonlyContentModelBlockGroup, + ReadonlyContentModelListItem, +} from 'roosterjs-content-model-types'; /** + * Search for all list items in the same thread as the current list item * @param model The content model * @param currentItem The current list item - * Search for all list items in the same thread as the current list item */ export function findListItemsInSameThread( group: ContentModelBlockGroup, currentItem: ContentModelListItem -): ContentModelListItem[] { +): ContentModelListItem[]; + +/** + * Search for all list items in the same thread as the current list item (Readonly) + * @param model The content model + * @param currentItem The current list item + */ +export function findListItemsInSameThread( + group: ReadonlyContentModelBlockGroup, + currentItem: ReadonlyContentModelListItem +): ReadonlyContentModelListItem[]; + +export function findListItemsInSameThread( + group: ReadonlyContentModelBlockGroup, + currentItem: ReadonlyContentModelListItem +): ReadonlyContentModelListItem[] { const items: (ContentModelListItem | null)[] = []; findListItems(group, items); @@ -16,7 +36,10 @@ export function findListItemsInSameThread( return filterListItems(items, currentItem); } -function findListItems(group: ContentModelBlockGroup, result: (ContentModelListItem | null)[]) { +function findListItems( + group: ReadonlyContentModelBlockGroup, + result: (ReadonlyContentModelListItem | null)[] +) { group.blocks.forEach(block => { switch (block.blockType) { case 'BlockGroup': @@ -56,7 +79,7 @@ function findListItems(group: ContentModelBlockGroup, result: (ContentModelListI }); } -function pushNullIfNecessary(result: (ContentModelListItem | null)[]) { +function pushNullIfNecessary(result: (ReadonlyContentModelListItem | null)[]) { const last = result[result.length - 1]; if (!last || last !== null) { @@ -65,10 +88,10 @@ function pushNullIfNecessary(result: (ContentModelListItem | null)[]) { } function filterListItems( - items: (ContentModelListItem | null)[], - currentItem: ContentModelListItem + items: (ReadonlyContentModelListItem | null)[], + currentItem: ReadonlyContentModelListItem ) { - const result: ContentModelListItem[] = []; + const result: ReadonlyContentModelListItem[] = []; const currentIndex = items.indexOf(currentItem); const levelLength = currentItem.levels.length; const isOrderedList = currentItem.levels[levelLength - 1]?.listType == 'OL'; @@ -131,7 +154,7 @@ function filterListItems( } function areListTypesCompatible( - listItems: (ContentModelListItem | null)[], + listItems: (ReadonlyContentModelListItem | null)[], currentIndex: number, compareToIndex: number ): boolean { @@ -146,7 +169,7 @@ function areListTypesCompatible( ); } -function hasStartNumberOverride(item: ContentModelListItem, levelLength: number): boolean { +function hasStartNumberOverride(item: ReadonlyContentModelListItem, levelLength: number): boolean { return item.levels .slice(0, levelLength) .some(level => level.format.startNumberOverride !== undefined); diff --git a/packages/roosterjs-content-model-core/test/coreApi/createContentModel/createContentModelTest.ts b/packages/roosterjs-content-model-core/test/coreApi/createContentModel/createContentModelTest.ts index 0b0ec01a507..bb223138b34 100644 --- a/packages/roosterjs-content-model-core/test/coreApi/createContentModel/createContentModelTest.ts +++ b/packages/roosterjs-content-model-core/test/coreApi/createContentModel/createContentModelTest.ts @@ -4,6 +4,7 @@ import * as domToContentModel from 'roosterjs-content-model-dom/lib/domToModel/d import * as updateCachedSelection from '../../../lib/corePlugin/cache/updateCachedSelection'; import { createContentModel } from '../../../lib/coreApi/createContentModel/createContentModel'; import { + ContentModelDocument, DomToModelContext, DomToModelOptionForCreateModel, EditorCore, @@ -362,7 +363,9 @@ describe('createContentModel and cache management', () => { }, } as any; - cloneModelSpy = spyOn(cloneModel, 'cloneModel').and.callFake(x => x); + cloneModelSpy = spyOn(cloneModel, 'cloneModel').and.callFake( + x => x as ContentModelDocument + ); spyOn(domToContentModel, 'domToContentModel').and.returnValue(mockedNewModel); diff --git a/packages/roosterjs-content-model-core/test/editor/EditorTest.ts b/packages/roosterjs-content-model-core/test/editor/EditorTest.ts index 042f2d0c9db..cb415755e7c 100644 --- a/packages/roosterjs-content-model-core/test/editor/EditorTest.ts +++ b/packages/roosterjs-content-model-core/test/editor/EditorTest.ts @@ -278,7 +278,9 @@ describe('Editor', () => { mockedModel ); - const cloneModelSpy = spyOn(cloneModel, 'cloneModel').and.callFake(x => x); + const cloneModelSpy = spyOn(cloneModel, 'cloneModel').and.callFake( + x => x as ContentModelDocument + ); const model = editor.getContentModelCopy('clean'); expect(model).toBe(mockedModel); diff --git a/packages/roosterjs-content-model-dom/lib/index.ts b/packages/roosterjs-content-model-dom/lib/index.ts index d871e3d46f2..519aa52801b 100644 --- a/packages/roosterjs-content-model-dom/lib/index.ts +++ b/packages/roosterjs-content-model-dom/lib/index.ts @@ -15,7 +15,7 @@ export { areSameFormats } from './domToModel/utils/areSameFormats'; export { isBlockElement } from './domToModel/utils/isBlockElement'; export { buildSelectionMarker } from './domToModel/utils/buildSelectionMarker'; -export { updateMetadata, hasMetadata } from './modelApi/metadata/updateMetadata'; +export { updateMetadata, getMetadata, hasMetadata } from './modelApi/metadata/updateMetadata'; export { isNodeOfType } from './domUtils/isNodeOfType'; export { isElementOfType } from './domUtils/isElementOfType'; export { getObjectKeys } from './domUtils/getObjectKeys'; @@ -130,10 +130,17 @@ export { retrieveModelFormatState } from './modelApi/editing/retrieveModelFormat export { getListStyleTypeFromString } from './modelApi/editing/getListStyleTypeFromString'; export { getSegmentTextFormat } from './modelApi/editing/getSegmentTextFormat'; -export { updateImageMetadata } from './modelApi/metadata/updateImageMetadata'; -export { updateTableCellMetadata } from './modelApi/metadata/updateTableCellMetadata'; -export { updateTableMetadata } from './modelApi/metadata/updateTableMetadata'; -export { updateListMetadata, ListMetadataDefinition } from './modelApi/metadata/updateListMetadata'; +export { updateImageMetadata, getImageMetadata } from './modelApi/metadata/updateImageMetadata'; +export { + updateTableCellMetadata, + getTableCellMetadata, +} from './modelApi/metadata/updateTableCellMetadata'; +export { updateTableMetadata, getTableMetadata } from './modelApi/metadata/updateTableMetadata'; +export { + updateListMetadata, + getListMetadata, + ListMetadataDefinition, +} from './modelApi/metadata/updateListMetadata'; export { ChangeSource } from './constants/ChangeSource'; export { BulletListType } from './constants/BulletListType'; diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/common/addBlock.ts b/packages/roosterjs-content-model-dom/lib/modelApi/common/addBlock.ts index 3461d6baccb..4c331427d7b 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/common/addBlock.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/common/addBlock.ts @@ -1,10 +1,13 @@ -import type { ContentModelBlock, ContentModelBlockGroup } from 'roosterjs-content-model-types'; +import type { + ContentModelBlock, + ShallowMutableContentModelBlockGroup, +} from 'roosterjs-content-model-types'; /** * Add a given block to block group * @param group The block group to add block into * @param block The block to add */ -export function addBlock(group: ContentModelBlockGroup, block: ContentModelBlock) { +export function addBlock(group: ShallowMutableContentModelBlockGroup, block: ContentModelBlock) { group.blocks.push(block); } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/common/addSegment.ts b/packages/roosterjs-content-model-dom/lib/modelApi/common/addSegment.ts index d564538490a..08535230a17 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/common/addSegment.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/common/addSegment.ts @@ -5,6 +5,8 @@ import type { ContentModelParagraph, ContentModelSegment, ContentModelSegmentFormat, + ShallowMutableContentModelBlockGroup, + ShallowMutableContentModelParagraph, } from 'roosterjs-content-model-types'; /** @@ -19,7 +21,28 @@ export function addSegment( newSegment: ContentModelSegment, blockFormat?: ContentModelBlockFormat, segmentFormat?: ContentModelSegmentFormat -): ContentModelParagraph { +): ContentModelParagraph; + +/** + * Add a given segment into a paragraph from its parent group. If the last block of the given group is not paragraph, create a new paragraph. (Shallow mutable) + * @param group The parent block group of the paragraph to add segment into + * @param newSegment The segment to add + * @param blockFormat The block format used for creating a new paragraph when need + * @returns The parent paragraph where the segment is added to + */ +export function addSegment( + group: ShallowMutableContentModelBlockGroup, + newSegment: ContentModelSegment, + blockFormat?: ContentModelBlockFormat, + segmentFormat?: ContentModelSegmentFormat +): ShallowMutableContentModelParagraph; + +export function addSegment( + group: ShallowMutableContentModelBlockGroup, + newSegment: ContentModelSegment, + blockFormat?: ContentModelBlockFormat, + segmentFormat?: ContentModelSegmentFormat +): ShallowMutableContentModelParagraph { const paragraph = ensureParagraph(group, blockFormat, segmentFormat); const lastSegment = paragraph.segments[paragraph.segments.length - 1]; diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/common/ensureParagraph.ts b/packages/roosterjs-content-model-dom/lib/modelApi/common/ensureParagraph.ts index e638f1920ce..0714d6c8e0e 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/common/ensureParagraph.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/common/ensureParagraph.ts @@ -1,10 +1,13 @@ import { addBlock } from './addBlock'; import { createParagraph } from '../creators/createParagraph'; +import { mutateBlock } from './mutate'; import type { ContentModelBlockFormat, ContentModelBlockGroup, ContentModelParagraph, ContentModelSegmentFormat, + ShallowMutableContentModelBlockGroup, + ShallowMutableContentModelParagraph, } from 'roosterjs-content-model-types'; /** @@ -17,11 +20,29 @@ export function ensureParagraph( group: ContentModelBlockGroup, blockFormat?: ContentModelBlockFormat, segmentFormat?: ContentModelSegmentFormat -): ContentModelParagraph { +): ContentModelParagraph; + +/** + * @internal + * Ensure there is a Paragraph that can insert segments in a Content Model Block Group (Shallow mutable) + * @param group The parent block group of the target paragraph + * @param blockFormat Format of the paragraph. This is only used if we need to create a new paragraph + */ +export function ensureParagraph( + group: ShallowMutableContentModelBlockGroup, + blockFormat?: ContentModelBlockFormat, + segmentFormat?: ContentModelSegmentFormat +): ShallowMutableContentModelParagraph; + +export function ensureParagraph( + group: ShallowMutableContentModelBlockGroup, + blockFormat?: ContentModelBlockFormat, + segmentFormat?: ContentModelSegmentFormat +): ShallowMutableContentModelParagraph { const lastBlock = group.blocks[group.blocks.length - 1]; if (lastBlock?.blockType == 'Paragraph') { - return lastBlock; + return mutateBlock(lastBlock); } else { const paragraph = createParagraph(true, blockFormat, segmentFormat); addBlock(group, paragraph); diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/editing/cloneModel.ts b/packages/roosterjs-content-model-dom/lib/modelApi/editing/cloneModel.ts index 95ee0cee0ed..b874b04a973 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/editing/cloneModel.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/editing/cloneModel.ts @@ -26,6 +26,26 @@ import type { ContentModelTableRow, ContentModelListLevel, CloneModelOptions, + ReadonlyContentModelDocument, + ReadonlyContentModelBlockGroupBase, + ReadonlyContentModelBlock, + ReadonlyContentModelFormatContainer, + ReadonlyContentModelBlockBase, + ReadonlyContentModelGeneralBlock, + ReadonlyContentModelListItem, + ReadonlyContentModelSelectionMarker, + ReadonlyContentModelSegmentBase, + ReadonlyContentModelWithDataset, + ReadonlyContentModelDivider, + ReadonlyContentModelListLevel, + ReadonlyContentModelParagraph, + ReadonlyContentModelSegment, + ReadonlyContentModelTable, + ReadonlyContentModelTableRow, + ReadonlyContentModelTableCell, + ReadonlyContentModelGeneralSegment, + ReadonlyContentModelImage, + ReadonlyContentModelText, } from 'roosterjs-content-model-types'; /** @@ -34,7 +54,7 @@ import type { * @param options @optional Options to specify customize the clone behavior */ export function cloneModel( - model: ContentModelDocument, + model: ReadonlyContentModelDocument, options?: CloneModelOptions ): ContentModelDocument { const newModel: ContentModelDocument = cloneBlockGroupBase(model, options || {}); @@ -46,7 +66,10 @@ export function cloneModel( return newModel; } -function cloneBlock(block: ContentModelBlock, options: CloneModelOptions): ContentModelBlock { +function cloneBlock( + block: ReadonlyContentModelBlock, + options: CloneModelOptions +): ContentModelBlock { switch (block.blockType) { case 'BlockGroup': switch (block.blockGroupType) { @@ -70,7 +93,7 @@ function cloneBlock(block: ContentModelBlock, options: CloneModelOptions): Conte } function cloneSegment( - segment: ContentModelSegment, + segment: ReadonlyContentModelSegment, options: CloneModelOptions ): ContentModelSegment { switch (segment.segmentType) { @@ -97,14 +120,16 @@ function cloneModelWithFormat( }; } -function cloneModelWithDataset(model: ContentModelWithDataset): ContentModelWithDataset { +function cloneModelWithDataset( + model: ReadonlyContentModelWithDataset +): ContentModelWithDataset { return { dataset: Object.assign({}, model.dataset), }; } function cloneBlockBase( - block: ContentModelBlockBase + block: ReadonlyContentModelBlockBase ): ContentModelBlockBase { const { blockType } = block; @@ -117,7 +142,7 @@ function cloneBlockBase( } function cloneBlockGroupBase( - group: ContentModelBlockGroupBase, + group: ReadonlyContentModelBlockGroupBase, options: CloneModelOptions ): ContentModelBlockGroupBase { const { blockGroupType, blocks } = group; @@ -129,7 +154,7 @@ function cloneBlockGroupBase( } function cloneSegmentBase( - segment: ContentModelSegmentBase + segment: ReadonlyContentModelSegmentBase ): ContentModelSegmentBase { const { segmentType, isSelected, code, link } = segment; @@ -165,7 +190,7 @@ function cloneEntity(entity: ContentModelEntity, options: CloneModelOptions): Co } function cloneParagraph( - paragraph: ContentModelParagraph, + paragraph: ReadonlyContentModelParagraph, options: CloneModelOptions ): ContentModelParagraph { const { cachedElement, segments, isImplicit, decorator, segmentFormat } = paragraph; @@ -193,7 +218,10 @@ function cloneParagraph( return newParagraph; } -function cloneTable(table: ContentModelTable, options: CloneModelOptions): ContentModelTable { +function cloneTable( + table: ReadonlyContentModelTable, + options: CloneModelOptions +): ContentModelTable { const { cachedElement, widths, rows } = table; return Object.assign( @@ -208,7 +236,7 @@ function cloneTable(table: ContentModelTable, options: CloneModelOptions): Conte } function cloneTableRow( - row: ContentModelTableRow, + row: ReadonlyContentModelTableRow, options: CloneModelOptions ): ContentModelTableRow { const { height, cells, cachedElement } = row; @@ -224,7 +252,7 @@ function cloneTableRow( } function cloneTableCell( - cell: ContentModelTableCell, + cell: ReadonlyContentModelTableCell, options: CloneModelOptions ): ContentModelTableCell { const { cachedElement, isSelected, spanAbove, spanLeft, isHeader } = cell; @@ -244,7 +272,7 @@ function cloneTableCell( } function cloneFormatContainer( - container: ContentModelFormatContainer, + container: ReadonlyContentModelFormatContainer, options: CloneModelOptions ): ContentModelFormatContainer { const { tagName, cachedElement } = container; @@ -262,7 +290,7 @@ function cloneFormatContainer( } function cloneListItem( - item: ContentModelListItem, + item: ReadonlyContentModelListItem, options: CloneModelOptions ): ContentModelListItem { const { formatHolder, levels, cachedElement } = item; @@ -278,13 +306,13 @@ function cloneListItem( ); } -function cloneListLevel(level: ContentModelListLevel): ContentModelListLevel { +function cloneListLevel(level: ReadonlyContentModelListLevel): ContentModelListLevel { const { listType } = level; return Object.assign({ listType }, cloneModelWithFormat(level), cloneModelWithDataset(level)); } function cloneDivider( - divider: ContentModelDivider, + divider: ReadonlyContentModelDivider, options: CloneModelOptions ): ContentModelDivider { const { tagName, isSelected, cachedElement } = divider; @@ -300,7 +328,7 @@ function cloneDivider( } function cloneGeneralBlock( - general: ContentModelGeneralBlock, + general: ReadonlyContentModelGeneralBlock, options: CloneModelOptions ): ContentModelGeneralBlock { const { element } = general; @@ -314,11 +342,13 @@ function cloneGeneralBlock( ); } -function cloneSelectionMarker(marker: ContentModelSelectionMarker): ContentModelSelectionMarker { +function cloneSelectionMarker( + marker: ReadonlyContentModelSelectionMarker +): ContentModelSelectionMarker { return Object.assign({ isSelected: marker.isSelected }, cloneSegmentBase(marker)); } -function cloneImage(image: ContentModelImage): ContentModelImage { +function cloneImage(image: ReadonlyContentModelImage): ContentModelImage { const { src, alt, title, isSelectedAsImageSelection } = image; return Object.assign( @@ -329,13 +359,13 @@ function cloneImage(image: ContentModelImage): ContentModelImage { } function cloneGeneralSegment( - general: ContentModelGeneralSegment, + general: ReadonlyContentModelGeneralSegment, options: CloneModelOptions ): ContentModelGeneralSegment { return Object.assign(cloneGeneralBlock(general, options), cloneSegmentBase(general)); } -function cloneText(textSegment: ContentModelText): ContentModelText { +function cloneText(textSegment: ReadonlyContentModelText): ContentModelText { const { text } = textSegment; return Object.assign({ text }, cloneSegmentBase(textSegment)); } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/editing/getClosestAncestorBlockGroupIndex.ts b/packages/roosterjs-content-model-dom/lib/modelApi/editing/getClosestAncestorBlockGroupIndex.ts index 27a95cef4c5..b680494215a 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/editing/getClosestAncestorBlockGroupIndex.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/editing/getClosestAncestorBlockGroupIndex.ts @@ -1,6 +1,7 @@ import type { ContentModelBlockGroup, ContentModelBlockGroupType, + ReadonlyContentModelBlockGroup, TypeOfBlockGroup, } from 'roosterjs-content-model-types'; @@ -11,7 +12,7 @@ import type { * @param stopTypes @optional Block group types that will cause stop searching */ export function getClosestAncestorBlockGroupIndex( - path: ContentModelBlockGroup[], + path: ReadonlyContentModelBlockGroup[], blockGroupTypes: TypeOfBlockGroup[], stopTypes: ContentModelBlockGroupType[] = [] ): number { diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateImageMetadata.ts b/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateImageMetadata.ts index 840bfa87014..bf5ca0bb4d0 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateImageMetadata.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateImageMetadata.ts @@ -1,10 +1,14 @@ -import { updateMetadata } from './updateMetadata'; +import { getMetadata, updateMetadata } from './updateMetadata'; import { createNumberDefinition, createObjectDefinition, createStringDefinition, } from './definitionCreators'; -import type { ContentModelImage, ImageMetadataFormat } from 'roosterjs-content-model-types'; +import type { + ContentModelImage, + ImageMetadataFormat, + ReadonlyContentModelImage, +} from 'roosterjs-content-model-types'; const NumberDefinition = createNumberDefinition(); @@ -21,6 +25,14 @@ const ImageMetadataFormatDefinition = createObjectDefinition = crea true /** allowNull */ ); +/** + * Get list metadata + * @param list The list Content Model (metadata holder) + */ +export function getListMetadata( + list: ReadonlyContentModelWithDataset +): ListMetadataFormat | null { + return getMetadata(list, ListMetadataDefinition); +} + /** * Update list metadata with a callback * @param list The list Content Model (metadata holder) * @param callback The callback function used for updating metadata */ export function updateListMetadata( - list: ContentModelWithDataset, + list: ShallowMutableContentModelWithDataset, callback?: (format: ListMetadataFormat | null) => ListMetadataFormat | null ): ListMetadataFormat | null { return updateMetadata(list, callback, ListMetadataDefinition); diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateMetadata.ts b/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateMetadata.ts index debd77304db..1e5fce4fbd7 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateMetadata.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateMetadata.ts @@ -1,8 +1,32 @@ import { validate } from './validate'; -import type { ContentModelWithDataset, Definition } from 'roosterjs-content-model-types'; +import type { + Definition, + ReadonlyContentModelWithDataset, + ShallowMutableContentModelWithDataset, +} from 'roosterjs-content-model-types'; const EditingInfoDatasetName = 'editingInfo'; +/** + * Retrieve metadata from the given model. + * @param model The Content Model to retrieve metadata from + * @param definition Definition of this metadata type, used for validate the metadata object + * @returns Metadata of the model, or null if it does not contain a valid metadata + */ +export function getMetadata( + model: ReadonlyContentModelWithDataset, + definition?: Definition +): T | null { + const metadataString = model.dataset[EditingInfoDatasetName]; + let obj: Object | null = null; + + try { + obj = JSON.parse(metadataString); + } catch {} + + return !definition || validate(obj, definition) ? (obj as T) : null; +} + /** * Update metadata of the given model * @param model The model to update metadata to @@ -11,20 +35,11 @@ const EditingInfoDatasetName = 'editingInfo'; * @returns The metadata object if any, or null */ export function updateMetadata( - model: ContentModelWithDataset, + model: ShallowMutableContentModelWithDataset, callback?: (metadata: T | null) => T | null, definition?: Definition ): T | null { - const metadataString = model.dataset[EditingInfoDatasetName]; - let obj: T | null = null; - - try { - obj = JSON.parse(metadataString) as T; - } catch {} - - if (definition && !validate(obj, definition)) { - obj = null; - } + let obj = getMetadata(model, definition); if (callback) { obj = callback(obj); @@ -43,6 +58,6 @@ export function updateMetadata( * Check if the given model has metadata * @param model The content model to check */ -export function hasMetadata(model: ContentModelWithDataset | HTMLElement): boolean { +export function hasMetadata(model: ReadonlyContentModelWithDataset | HTMLElement): boolean { return !!model.dataset[EditingInfoDatasetName]; } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateTableCellMetadata.ts b/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateTableCellMetadata.ts index 274cd905063..f718596fc71 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateTableCellMetadata.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateTableCellMetadata.ts @@ -1,6 +1,10 @@ import { createBooleanDefinition, createObjectDefinition } from './definitionCreators'; -import { updateMetadata } from './updateMetadata'; -import type { ContentModelTableCell, TableCellMetadataFormat } from 'roosterjs-content-model-types'; +import { getMetadata, updateMetadata } from './updateMetadata'; +import type { + ReadonlyContentModelTableCell, + ShallowMutableContentModelTableCell, + TableCellMetadataFormat, +} from 'roosterjs-content-model-types'; const TableCellMetadataFormatDefinition = createObjectDefinition>( { @@ -12,13 +16,23 @@ const TableCellMetadataFormatDefinition = createObjectDefinition TableCellMetadataFormat | null ): TableCellMetadataFormat | null { return updateMetadata(cell, callback, TableCellMetadataFormatDefinition); diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateTableMetadata.ts b/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateTableMetadata.ts index 0ad6985f958..cc9bd3ef3bb 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateTableMetadata.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/metadata/updateTableMetadata.ts @@ -1,12 +1,16 @@ +import { getMetadata, updateMetadata } from './updateMetadata'; import { TableBorderFormat } from '../../constants/TableBorderFormat'; -import { updateMetadata } from './updateMetadata'; import { createBooleanDefinition, createNumberDefinition, createObjectDefinition, createStringDefinition, } from './definitionCreators'; -import type { ContentModelTable, TableMetadataFormat } from 'roosterjs-content-model-types'; +import type { + ReadonlyContentModelTable, + ShallowMutableContentModelTable, + TableMetadataFormat, +} from 'roosterjs-content-model-types'; const NullStringDefinition = createStringDefinition( false /** isOptional */, @@ -40,13 +44,21 @@ const TableFormatDefinition = createObjectDefinition TableMetadataFormat | null ): TableMetadataFormat | null { return updateMetadata(table, callback, TableFormatDefinition); diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/selection/collectSelections.ts b/packages/roosterjs-content-model-dom/lib/modelApi/selection/collectSelections.ts index eeb023bb2c1..4d6c2c8e4f4 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/selection/collectSelections.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/selection/collectSelections.ts @@ -1,6 +1,7 @@ import { getClosestAncestorBlockGroupIndex } from '../editing/getClosestAncestorBlockGroupIndex'; import { isBlockGroupOfType } from '../typeCheck/isBlockGroupOfType'; import { iterateSelections } from './iterateSelections'; +import { mutateBlock } from '../common/mutate'; import type { ContentModelBlock, ContentModelBlockGroup, @@ -12,46 +13,126 @@ import type { ContentModelTable, IterateSelectionsOption, OperationalBlocks, + ReadonlyContentModelBlock, + ReadonlyContentModelBlockGroup, + ReadonlyContentModelDocument, + ReadonlyContentModelListItem, + ReadonlyContentModelParagraph, + ReadonlyContentModelSegment, + ReadonlyContentModelTable, + ReadonlyOperationalBlocks, + ReadonlyTableSelectionContext, + ShallowMutableContentModelParagraph, + ShallowMutableContentModelSegment, TableSelectionContext, TypeOfBlockGroup, } from 'roosterjs-content-model-types'; +//#region getSelectedSegmentsAndParagraphs /** * Get an array of selected parent paragraph and child segment pair * @param model The Content Model to get selection from * @param includingFormatHolder True means also include format holder as segment from list item, in that case paragraph will be null + * @param includingEntity True to include entity in result as well */ export function getSelectedSegmentsAndParagraphs( model: ContentModelDocument, includingFormatHolder: boolean, includingEntity?: boolean -): [ContentModelSegment, ContentModelParagraph | null, ContentModelBlockGroup[]][] { +): [ContentModelSegment, ContentModelParagraph | null, ContentModelBlockGroup[]][]; + +/** + * Get an array of selected parent paragraph and child segment pair, return mutable paragraph and segments + * @param model The Content Model to get selection from + * @param includingFormatHolder True means also include format holder as segment from list item, in that case paragraph will be null + * @param includingEntity True to include entity in result as well + * @param mutate Set to true to indicate we will mutate the selected paragraphs + */ +export function getSelectedSegmentsAndParagraphs( + model: ReadonlyContentModelDocument, + includingFormatHolder: boolean, + includingEntity: boolean, + mutate: true +): [ + ShallowMutableContentModelSegment, + ContentModelParagraph | null, + ReadonlyContentModelBlockGroup[] +][]; + +/** + * Get an array of selected parent paragraph and child segment pair (Readonly) + * @param model The Content Model to get selection from + * @param includingFormatHolder True means also include format holder as segment from list item, in that case paragraph will be null + * @param includingEntity True to include entity in result as well + */ +export function getSelectedSegmentsAndParagraphs( + model: ReadonlyContentModelDocument, + includingFormatHolder: boolean, + includingEntity?: boolean +): [ + ReadonlyContentModelSegment, + ReadonlyContentModelParagraph | null, + ReadonlyContentModelBlockGroup[] +][]; + +export function getSelectedSegmentsAndParagraphs( + model: ReadonlyContentModelDocument, + includingFormatHolder: boolean, + includingEntity?: boolean, + mutate?: boolean +): [ + ReadonlyContentModelSegment, + ReadonlyContentModelParagraph | null, + ReadonlyContentModelBlockGroup[] +][] { const selections = collectSelections(model, { includeListFormatHolder: includingFormatHolder ? 'allSegments' : 'never', }); const result: [ - ContentModelSegment, - ContentModelParagraph | null, - ContentModelBlockGroup[] + ReadonlyContentModelSegment, + ReadonlyContentModelParagraph | null, + ReadonlyContentModelBlockGroup[] ][] = []; selections.forEach(({ segments, block, path }) => { - if (segments && ((includingFormatHolder && !block) || block?.blockType == 'Paragraph')) { - segments.forEach(segment => { - if ( - includingEntity || - segment.segmentType != 'Entity' || - !segment.entityFormat.isReadonly - ) { - result.push([segment, block?.blockType == 'Paragraph' ? block : null, path]); + if (segments) { + if ( + includingFormatHolder && + !block && + segments.length == 1 && + path[0].blockGroupType == 'ListItem' && + segments[0] == path[0].formatHolder + ) { + const list = path[0]; + + if (mutate) { + mutateBlock(list); } - }); + + result.push([list.formatHolder, null, path]); + } else if (block?.blockType == 'Paragraph') { + if (mutate) { + mutateBlock(block); + } + + segments.forEach(segment => { + if ( + includingEntity || + segment.segmentType != 'Entity' || + !segment.entityFormat.isReadonly + ) { + result.push([segment, block, path]); + } + }); + } } }); return result; } +//#endregion +//#region getSelectedSegments /** * Get an array of selected segments from a content model * @param model The Content Model to get selection from @@ -60,29 +141,93 @@ export function getSelectedSegmentsAndParagraphs( export function getSelectedSegments( model: ContentModelDocument, includingFormatHolder: boolean -): ContentModelSegment[] { - return getSelectedSegmentsAndParagraphs(model, includingFormatHolder).map(x => x[0]); +): ContentModelSegment[]; + +/** + * Get an array of selected segments from a content model, return mutable segments + * @param model The Content Model to get selection from + * @param includingFormatHolder True means also include format holder as segment from list item + * @param mutate Set to true to indicate we will mutate the selected paragraphs + */ +export function getSelectedSegments( + model: ReadonlyContentModelDocument, + includingFormatHolder: boolean, + mutate: true +): ShallowMutableContentModelSegment[]; + +/** + * Get an array of selected segments from a content model (Readonly) + * @param model The Content Model to get selection from + * @param includingFormatHolder True means also include format holder as segment from list item + */ +export function getSelectedSegments( + model: ReadonlyContentModelDocument, + includingFormatHolder: boolean +): ReadonlyContentModelSegment[]; + +export function getSelectedSegments( + model: ReadonlyContentModelDocument, + includingFormatHolder: boolean, + mutate?: boolean +): ReadonlyContentModelSegment[] { + const segments = mutate + ? getSelectedSegmentsAndParagraphs( + model, + includingFormatHolder, + false /*includeEntity*/, + true /*mutate*/ + ) + : getSelectedSegmentsAndParagraphs(model, includingFormatHolder); + + return segments.map(x => x[0]); } +//#endregion +//#region getSelectedParagraphs /** * Get any array of selected paragraphs from a content model * @param model The Content Model to get selection from */ -export function getSelectedParagraphs(model: ContentModelDocument): ContentModelParagraph[] { +export function getSelectedParagraphs(model: ContentModelDocument): ContentModelParagraph[]; + +/** + * Get any array of selected paragraphs from a content model, return mutable paragraphs + * @param model The Content Model to get selection from + * @param mutate Set to true to indicate we will mutate the selected paragraphs + */ +export function getSelectedParagraphs( + model: ReadonlyContentModelDocument, + mutate: true +): ShallowMutableContentModelParagraph[]; + +/** + * Get any array of selected paragraphs from a content model (Readonly) + * @param model The Content Model to get selection from + */ +export function getSelectedParagraphs( + model: ReadonlyContentModelDocument +): ReadonlyContentModelParagraph[]; + +export function getSelectedParagraphs( + model: ReadonlyContentModelDocument, + mutate?: boolean +): ReadonlyContentModelParagraph[] { const selections = collectSelections(model, { includeListFormatHolder: 'never' }); - const result: ContentModelParagraph[] = []; + const result: ReadonlyContentModelParagraph[] = []; removeUnmeaningfulSelections(selections); selections.forEach(({ block }) => { if (block?.blockType == 'Paragraph') { - result.push(block); + result.push(mutate ? mutateBlock(block) : block); } }); return result; } +//#endregion +//#region getOperationalBlocks /** * Get an array of block group - block pair that is of the expected block group type from selection * @param group The root block group to search @@ -95,8 +240,29 @@ export function getOperationalBlocks( blockGroupTypes: TypeOfBlockGroup[], stopTypes: ContentModelBlockGroupType[], deepFirst?: boolean -): OperationalBlocks[] { - const result: OperationalBlocks[] = []; +): OperationalBlocks[]; + +/** + * Get an array of block group - block pair that is of the expected block group type from selection (Readonly) + * @param group The root block group to search + * @param blockGroupTypes The expected block group types + * @param stopTypes Block group types that will stop searching when hit + * @param deepFirst True means search in deep first, otherwise wide first + */ +export function getOperationalBlocks( + group: ReadonlyContentModelBlockGroup, + blockGroupTypes: TypeOfBlockGroup[], + stopTypes: ContentModelBlockGroupType[], + deepFirst?: boolean +): ReadonlyOperationalBlocks[]; + +export function getOperationalBlocks( + group: ReadonlyContentModelBlockGroup, + blockGroupTypes: TypeOfBlockGroup[], + stopTypes: ContentModelBlockGroupType[], + deepFirst?: boolean +): ReadonlyOperationalBlocks[] { + const result: ReadonlyOperationalBlocks[] = []; const findSequence = deepFirst ? blockGroupTypes.map(type => [type]) : [blockGroupTypes]; const selections = collectSelections(group, { includeListFormatHolder: 'never', @@ -131,17 +297,31 @@ export function getOperationalBlocks( return result; } +//#endregion +//#region getFirstSelectedTable /** * Get the first selected table from content model * @param model The Content Model to get selection from */ export function getFirstSelectedTable( model: ContentModelDocument -): [ContentModelTable | undefined, ContentModelBlockGroup[]] { +): [ContentModelTable | undefined, ContentModelBlockGroup[]]; + +/** + * Get the first selected table from content model (Readonly) + * @param model The Content Model to get selection from + */ +export function getFirstSelectedTable( + model: ReadonlyContentModelDocument +): [ReadonlyContentModelTable | undefined, ReadonlyContentModelBlockGroup[]]; + +export function getFirstSelectedTable( + model: ReadonlyContentModelDocument +): [ReadonlyContentModelTable | undefined, ReadonlyContentModelBlockGroup[]] { const selections = collectSelections(model, { includeListFormatHolder: 'never' }); - let table: ContentModelTable | undefined; - let resultPath: ContentModelBlockGroup[] = []; + let table: ReadonlyContentModelTable | undefined; + let resultPath: ReadonlyContentModelBlockGroup[] = []; removeUnmeaningfulSelections(selections); @@ -164,14 +344,28 @@ export function getFirstSelectedTable( return [table, resultPath]; } +//#endregion +//#region getFirstSelectedListItem /** * Get the first selected list item from content model * @param model The Content Model to get selection from */ export function getFirstSelectedListItem( model: ContentModelDocument -): ContentModelListItem | undefined { +): ContentModelListItem | undefined; + +/** + * Get the first selected list item from content model (Readonly) + * @param model The Content Model to get selection from + */ +export function getFirstSelectedListItem( + model: ReadonlyContentModelDocument +): ReadonlyContentModelListItem | undefined; + +export function getFirstSelectedListItem( + model: ReadonlyContentModelDocument +): ReadonlyContentModelListItem | undefined { let listItem: ContentModelListItem | undefined; getOperationalBlocks(model, ['ListItem'], ['TableCell']).forEach(r => { @@ -182,7 +376,9 @@ export function getFirstSelectedListItem( return listItem; } +//#endregion +//#region collectSelections interface SelectionInfo { path: ContentModelBlockGroup[]; segments?: ContentModelSegment[]; @@ -190,11 +386,28 @@ interface SelectionInfo { tableContext?: TableSelectionContext; } +interface ReadonlySelectionInfo { + path: ReadonlyContentModelBlockGroup[]; + segments?: ReadonlyContentModelSegment[]; + block?: ReadonlyContentModelBlock; + tableContext?: ReadonlyTableSelectionContext; +} + function collectSelections( group: ContentModelBlockGroup, option?: IterateSelectionsOption -): SelectionInfo[] { - const selections: SelectionInfo[] = []; +): SelectionInfo[]; + +function collectSelections( + group: ReadonlyContentModelBlockGroup, + option?: IterateSelectionsOption +): ReadonlySelectionInfo[]; + +function collectSelections( + group: ReadonlyContentModelBlockGroup, + option?: IterateSelectionsOption +): ReadonlySelectionInfo[] { + const selections: ReadonlySelectionInfo[] = []; iterateSelections( group, @@ -211,8 +424,10 @@ function collectSelections( return selections; } +//#endregion -function removeUnmeaningfulSelections(selections: SelectionInfo[]) { +//#region utils +function removeUnmeaningfulSelections(selections: ReadonlySelectionInfo[]) { if ( selections.length > 1 && isOnlySelectionMarkerSelected(selections, false /*checkFirstParagraph*/) @@ -230,7 +445,7 @@ function removeUnmeaningfulSelections(selections: SelectionInfo[]) { } function isOnlySelectionMarkerSelected( - selections: SelectionInfo[], + selections: ReadonlySelectionInfo[], checkFirstParagraph: boolean ): boolean { const selection = selections[checkFirstParagraph ? 0 : selections.length - 1]; @@ -252,3 +467,4 @@ function isOnlySelectionMarkerSelected( return false; } } +//#endregion diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/selection/iterateSelections.ts b/packages/roosterjs-content-model-dom/lib/modelApi/selection/iterateSelections.ts index 9fe47705b7f..05db43d0348 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/selection/iterateSelections.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/selection/iterateSelections.ts @@ -1,10 +1,12 @@ import type { ContentModelBlockGroup, ContentModelBlockWithCache, - ContentModelSegment, IterateSelectionsCallback, IterateSelectionsOption, - TableSelectionContext, + ReadonlyContentModelBlockGroup, + ReadonlyContentModelSegment, + ReadonlyIterateSelectionsCallback, + ReadonlyTableSelectionContext, } from 'roosterjs-content-model-types'; /** @@ -17,23 +19,46 @@ export function iterateSelections( group: ContentModelBlockGroup, callback: IterateSelectionsCallback, option?: IterateSelectionsOption +): void; + +/** + * Iterate all selected elements in a given model (Readonly) + * @param group The given Content Model to iterate selection from + * @param callback The callback function to access the selected element + * @param option Option to determine how to iterate + */ +export function iterateSelections( + group: ReadonlyContentModelBlockGroup, + callback: ReadonlyIterateSelectionsCallback, + option?: IterateSelectionsOption +): void; + +export function iterateSelections( + group: ReadonlyContentModelBlockGroup, + callback: ReadonlyIterateSelectionsCallback | IterateSelectionsCallback, + option?: IterateSelectionsOption ): void { - const internalCallback: IterateSelectionsCallback = (path, tableContext, block, segments) => { + const internalCallback: ReadonlyIterateSelectionsCallback = ( + path, + tableContext, + block, + segments + ) => { if (!!(block as ContentModelBlockWithCache)?.cachedElement) { delete (block as ContentModelBlockWithCache).cachedElement; } - return callback(path, tableContext, block, segments); + return (callback as ReadonlyIterateSelectionsCallback)(path, tableContext, block, segments); }; internalIterateSelections([group], internalCallback, option); } function internalIterateSelections( - path: ContentModelBlockGroup[], - callback: IterateSelectionsCallback, + path: ReadonlyContentModelBlockGroup[], + callback: ReadonlyIterateSelectionsCallback, option?: IterateSelectionsOption, - table?: TableSelectionContext, + table?: ReadonlyTableSelectionContext, treatAllAsSelect?: boolean ): boolean { const parent = path[0]; @@ -104,7 +129,7 @@ function internalIterateSelections( continue; } - const newTable: TableSelectionContext = { + const newTable: ReadonlyTableSelectionContext = { table: block, rowIndex, colIndex, @@ -141,7 +166,7 @@ function internalIterateSelections( break; case 'Paragraph': - const segments: ContentModelSegment[] = []; + const segments: ReadonlyContentModelSegment[] = []; for (let i = 0; i < block.segments.length; i++) { const segment = block.segments[i]; diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/typeCheck/isBlockGroupOfType.ts b/packages/roosterjs-content-model-dom/lib/modelApi/typeCheck/isBlockGroupOfType.ts index a851e2fe166..afadd639e39 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/typeCheck/isBlockGroupOfType.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/typeCheck/isBlockGroupOfType.ts @@ -1,6 +1,8 @@ import type { ContentModelBlock, ContentModelBlockGroup, + ReadonlyContentModelBlock, + ReadonlyContentModelBlockGroup, TypeOfBlockGroup, } from 'roosterjs-content-model-types'; @@ -12,6 +14,29 @@ import type { export function isBlockGroupOfType( input: ContentModelBlock | ContentModelBlockGroup | null | undefined, type: TypeOfBlockGroup +): input is T; + +/** + * Check if the given content model block or block group is of the expected block group type (Readonly) + * @param input The object to check + * @param type The expected type + */ +export function isBlockGroupOfType( + input: ReadonlyContentModelBlock | ReadonlyContentModelBlockGroup | null | undefined, + type: TypeOfBlockGroup +): input is T; + +export function isBlockGroupOfType< + T extends ContentModelBlockGroup | ReadonlyContentModelBlockGroup +>( + input: + | ReadonlyContentModelBlock + | ReadonlyContentModelBlockGroup + | ContentModelBlock + | ContentModelBlockGroup + | null + | undefined, + type: TypeOfBlockGroup ): input is T { const item = input; diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/typeCheck/isGeneralSegment.ts b/packages/roosterjs-content-model-dom/lib/modelApi/typeCheck/isGeneralSegment.ts index 56163aa0f8b..f7baf3d6e68 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/typeCheck/isGeneralSegment.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/typeCheck/isGeneralSegment.ts @@ -1,6 +1,10 @@ import type { ContentModelBlockGroup, ContentModelGeneralSegment, + ReadonlyContentModelBlockGroup, + ReadonlyContentModelGeneralSegment, + ShallowMutableContentModelBlockGroup, + ShallowMutableContentModelGeneralSegment, } from 'roosterjs-content-model-types'; /** @@ -9,6 +13,26 @@ import type { */ export function isGeneralSegment( group: ContentModelBlockGroup | ContentModelGeneralSegment +): group is ContentModelGeneralSegment; + +/** + * Check if the given block group is a general segment (Shallow mutable) + * @param group The group to check + */ +export function isGeneralSegment( + group: ShallowMutableContentModelBlockGroup | ShallowMutableContentModelGeneralSegment +): group is ShallowMutableContentModelGeneralSegment; + +/** + * Check if the given block group is a general segment (Readonly) + * @param group The group to check + */ +export function isGeneralSegment( + group: ReadonlyContentModelBlockGroup | ReadonlyContentModelGeneralSegment +): group is ReadonlyContentModelGeneralSegment; + +export function isGeneralSegment( + group: ReadonlyContentModelBlockGroup | ReadonlyContentModelGeneralSegment ): group is ContentModelGeneralSegment { return ( group.blockGroupType == 'General' && diff --git a/packages/roosterjs-content-model-dom/test/modelApi/editing/retrieveModelFormatStateTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/editing/retrieveModelFormatStateTest.ts index accfa4a4f09..6e4e485bdf5 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/editing/retrieveModelFormatStateTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/editing/retrieveModelFormatStateTest.ts @@ -60,7 +60,7 @@ describe('retrieveModelFormatState', () => { const para = createParagraph(); const marker = createSelectionMarker(segmentFormat); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [marker]); return false; }); @@ -78,7 +78,7 @@ describe('retrieveModelFormatState', () => { addCode(marker, { format: { fontFamily: 'monospace' } }); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [marker]); return false; }); @@ -100,7 +100,7 @@ describe('retrieveModelFormatState', () => { const listItem = createListItem([createListLevel('OL')]); const marker = createSelectionMarker(segmentFormat); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((_, callback) => { callback([listItem], undefined, para, [marker]); return false; }); @@ -123,7 +123,7 @@ describe('retrieveModelFormatState', () => { const quote = createFormatContainer('blockquote'); const marker = createSelectionMarker(segmentFormat); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((_, callback) => { callback([quote], undefined, para, [marker]); return false; }); @@ -146,7 +146,7 @@ describe('retrieveModelFormatState', () => { }); const marker = createSelectionMarker(segmentFormat); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [marker]); return false; }); @@ -171,7 +171,7 @@ describe('retrieveModelFormatState', () => { const para = createParagraph(false, paraFormat); const marker = createSelectionMarker(segmentFormat); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [marker]); return false; }); @@ -196,7 +196,7 @@ describe('retrieveModelFormatState', () => { table.rows[0].cells.push(cell); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback( [path], { @@ -233,7 +233,7 @@ describe('retrieveModelFormatState', () => { table.rows[0].cells.push(cell); applyTableFormat(table); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback( [path], { @@ -283,7 +283,7 @@ describe('retrieveModelFormatState', () => { table.rows[0].cells.push(cell1, cell2); model.blocks.push(table); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], { table: table, rowIndex: 0, @@ -310,7 +310,7 @@ describe('retrieveModelFormatState', () => { const marker1 = createSelectionMarker(segmentFormat); const marker2 = createSelectionMarker(); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para1, [marker1]); callback([path], undefined, para2, [marker2]); return false; @@ -345,7 +345,7 @@ describe('retrieveModelFormatState', () => { const text2 = createText('test2', { fontFamily: 'Arial' }); const result: ContentModelFormatState = {}; - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [text1, text2]); return false; }); @@ -371,7 +371,7 @@ describe('retrieveModelFormatState', () => { const text2 = createText('test2', { fontFamily: 'Times' }); const result: ContentModelFormatState = {}; - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [text1, text2]); return false; }); @@ -396,7 +396,7 @@ describe('retrieveModelFormatState', () => { const marker = createSelectionMarker({ fontFamily: 'Times' }); const result: ContentModelFormatState = {}; - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [text, marker]); return false; }); @@ -422,7 +422,7 @@ describe('retrieveModelFormatState', () => { const divider = createDivider('hr'); const marker1 = createSelectionMarker(segmentFormat); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para1, [marker1]); callback([path], undefined, divider); return false; @@ -445,7 +445,7 @@ describe('retrieveModelFormatState', () => { const divider = createDivider('hr'); const marker1 = createSelectionMarker(segmentFormat); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, divider); callback([path], undefined, para1, [marker1]); return false; @@ -472,7 +472,7 @@ describe('retrieveModelFormatState', () => { textColor: 'block', }; - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para1, [marker1]); return false; }); @@ -623,7 +623,7 @@ describe('retrieveModelFormatState', () => { image.isSelected = true; para.segments.push(image); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [image]); return false; }); @@ -663,7 +663,7 @@ describe('retrieveModelFormatState', () => { para.segments.push(image); para.segments.push(image2); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [image, image2]); return false; }); @@ -692,7 +692,7 @@ describe('retrieveModelFormatState', () => { const marker = createSelectionMarker(); para.segments.push(marker); - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [marker]); return false; }); @@ -727,7 +727,7 @@ describe('retrieveModelFormatState', () => { text1.isSelected = true; - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [text1]); return false; }); @@ -761,7 +761,7 @@ describe('retrieveModelFormatState', () => { text1.isSelected = true; text2.isSelected = true; - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [text1, text2]); return false; }); @@ -791,7 +791,7 @@ describe('retrieveModelFormatState', () => { text1.isSelected = true; text2.isSelected = true; - spyOn(iterateSelections, 'iterateSelections').and.callFake((path, callback) => { + spyOn(iterateSelections, 'iterateSelections').and.callFake((path: any, callback) => { callback([path], undefined, para, [text1, text2]); return false; }); diff --git a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateImageMetadataTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateImageMetadataTest.ts index fa1d7115695..1912b6b21a4 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateImageMetadataTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateImageMetadataTest.ts @@ -1,5 +1,75 @@ import { ContentModelImage, ImageMetadataFormat } from 'roosterjs-content-model-types'; -import { updateImageMetadata } from '../../../lib/modelApi/metadata/updateImageMetadata'; +import { + getImageMetadata, + updateImageMetadata, +} from '../../../lib/modelApi/metadata/updateImageMetadata'; + +describe('getImageMetadataTest', () => { + it('No value', () => { + const image: ContentModelImage = { + segmentType: 'Image', + format: {}, + src: 'test', + dataset: {}, + }; + + const result = getImageMetadata(image); + + expect(result).toBeNull(); + }); + + it('Empty value', () => { + const image: ContentModelImage = { + segmentType: 'Image', + format: {}, + src: 'test', + dataset: { + editingInfo: '', + }, + }; + + const result = getImageMetadata(image); + + expect(result).toBeNull(); + }); + + it('Full valid value, return original value', () => { + const imageFormat: ImageMetadataFormat = { + widthPx: 1, + heightPx: 2, + leftPercent: 3, + rightPercent: 4, + topPercent: 5, + bottomPercent: 6, + angleRad: 7, + naturalHeight: 8, + naturalWidth: 9, + src: 'test', + }; + const image: ContentModelImage = { + segmentType: 'Image', + format: {}, + src: 'test', + dataset: { + editingInfo: JSON.stringify(imageFormat), + }, + }; + const result = getImageMetadata(image); + + expect(result).toEqual({ + widthPx: 1, + heightPx: 2, + leftPercent: 3, + rightPercent: 4, + topPercent: 5, + bottomPercent: 6, + angleRad: 7, + naturalHeight: 8, + naturalWidth: 9, + src: 'test', + }); + }); +}); describe('updateImageMetadataTest', () => { it('No value', () => { diff --git a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateListMetadataTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateListMetadataTest.ts index 528746e83e2..ed49e4af6a8 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateListMetadataTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateListMetadataTest.ts @@ -1,5 +1,48 @@ import { ContentModelWithDataset, ListMetadataFormat } from 'roosterjs-content-model-types'; -import { updateListMetadata } from '../../../lib/modelApi/metadata/updateListMetadata'; +import { + getListMetadata, + updateListMetadata, +} from '../../../lib/modelApi/metadata/updateListMetadata'; + +describe('getListMetadata', () => { + it('No value', () => { + const list: ContentModelWithDataset = { + dataset: {}, + }; + const result = getListMetadata(list); + + expect(result).toBeNull(); + }); + + it('Empty value', () => { + const list: ContentModelWithDataset = { + dataset: { + editingInfo: '', + }, + }; + const result = getListMetadata(list); + + expect(result).toBeNull(); + }); + + it('Full valid value, return original value', () => { + const listFormat: ListMetadataFormat = { + orderedStyleType: 2, + unorderedStyleType: 3, + }; + const list: ContentModelWithDataset = { + dataset: { + editingInfo: JSON.stringify(listFormat), + }, + }; + const result = getListMetadata(list); + + expect(result).toEqual({ + orderedStyleType: 2, + unorderedStyleType: 3, + }); + }); +}); describe('updateListMetadata', () => { it('No value', () => { diff --git a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateMetadataTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateMetadataTest.ts index 081280cc381..9dc34a783b3 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateMetadataTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateMetadataTest.ts @@ -1,6 +1,97 @@ import * as validate from '../../../lib/modelApi/metadata/validate'; -import { ContentModelWithDataset, Definition } from 'roosterjs-content-model-types'; -import { hasMetadata, updateMetadata } from '../../../lib/modelApi/metadata/updateMetadata'; +import { + getMetadata, + hasMetadata, + updateMetadata, +} from '../../../lib/modelApi/metadata/updateMetadata'; +import { + ContentModelWithDataset, + Definition, + ReadonlyContentModelWithDataset, +} from 'roosterjs-content-model-types'; + +describe('getMetadata', () => { + it('no metadata', () => { + const model: ReadonlyContentModelWithDataset = { + dataset: {}, + }; + const result = getMetadata(model); + + expect(model).toEqual({ + dataset: {}, + }); + expect(result).toBeNull(); + }); + + it('with metadata', () => { + const model: ReadonlyContentModelWithDataset = { + dataset: { + editingInfo: '{"a":"b"}', + }, + }; + + const result = getMetadata(model); + + expect(model).toEqual({ + dataset: { + editingInfo: '{"a":"b"}', + }, + }); + expect(result).toEqual({ + a: 'b', + }); + }); + + it('with metadata, pass the validation', () => { + const model: ContentModelWithDataset = { + dataset: { + editingInfo: '{"a":"b"}', + }, + }; + + const validateSpy = spyOn(validate, 'validate').and.returnValue(true); + + const mockedDefinition = 'DEFINITION' as any; + const result = getMetadata(model, mockedDefinition); + + expect(validateSpy).toHaveBeenCalledWith( + { + a: 'b', + }, + mockedDefinition + ); + expect(model).toEqual({ + dataset: { editingInfo: '{"a":"b"}' }, + }); + expect(result).toEqual({ + a: 'b', + }); + }); + + it('with metadata, fail the validation, return new value', () => { + const model: ContentModelWithDataset = { + dataset: { + editingInfo: '{"a":"b"}', + }, + }; + + const validateSpy = spyOn(validate, 'validate').and.returnValue(false); + + const mockedDefinition = 'DEFINITION' as any; + const result = getMetadata(model, mockedDefinition); + + expect(validateSpy).toHaveBeenCalledWith( + { + a: 'b', + }, + mockedDefinition + ); + expect(model).toEqual({ + dataset: { editingInfo: '{"a":"b"}' }, + }); + expect(result).toBeNull(); + }); +}); describe('updateMetadata', () => { it('no metadata', () => { diff --git a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateTableCellMetadataTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateTableCellMetadataTest.ts index bf0bbd273b3..bf43f76c1f0 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateTableCellMetadataTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateTableCellMetadataTest.ts @@ -1,5 +1,61 @@ import { ContentModelTableCell, TableCellMetadataFormat } from 'roosterjs-content-model-types'; -import { updateTableCellMetadata } from '../../../lib//modelApi/metadata/updateTableCellMetadata'; +import { + getTableCellMetadata, + updateTableCellMetadata, +} from '../../../lib//modelApi/metadata/updateTableCellMetadata'; + +describe('getTableCellMetadata', () => { + it('No value', () => { + const cell: ContentModelTableCell = { + blockGroupType: 'TableCell', + format: {}, + blocks: [], + spanAbove: false, + spanLeft: false, + dataset: {}, + }; + const result = getTableCellMetadata(cell); + + expect(result).toBeNull(); + }); + + it('Empty value', () => { + const cell: ContentModelTableCell = { + blockGroupType: 'TableCell', + format: {}, + blocks: [], + spanAbove: false, + spanLeft: false, + dataset: { + editingInfo: '', + }, + }; + const result = getTableCellMetadata(cell); + + expect(result).toBeNull(); + }); + + it('Full valid value, return original value', () => { + const cellFormat: TableCellMetadataFormat = { + bgColorOverride: true, + }; + const cell: ContentModelTableCell = { + blockGroupType: 'TableCell', + format: {}, + blocks: [], + spanAbove: false, + spanLeft: false, + dataset: { + editingInfo: JSON.stringify(cellFormat), + }, + }; + const result = getTableCellMetadata(cell); + + expect(result).toEqual({ + bgColorOverride: true, + }); + }); +}); describe('updateTableCellMetadata', () => { it('No value', () => { diff --git a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateTableMetadataTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateTableMetadataTest.ts index 250731ca03b..1501e5c9137 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateTableMetadataTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/metadata/updateTableMetadataTest.ts @@ -1,6 +1,81 @@ import { ContentModelTable, TableMetadataFormat } from 'roosterjs-content-model-types'; import { TableBorderFormat } from '../../../lib/constants/TableBorderFormat'; -import { updateTableMetadata } from '../../../lib/modelApi/metadata/updateTableMetadata'; +import { + getTableMetadata, + updateTableMetadata, +} from '../../../lib/modelApi/metadata/updateTableMetadata'; + +describe('getTableMetadata', () => { + it('No value', () => { + const table: ContentModelTable = { + blockType: 'Table', + format: {}, + rows: [], + widths: [], + dataset: {}, + }; + const result = getTableMetadata(table); + + expect(result).toBeNull(); + }); + + it('Empty value', () => { + const table: ContentModelTable = { + blockType: 'Table', + format: {}, + rows: [], + widths: [], + dataset: { + editingInfo: '', + }, + }; + const result = getTableMetadata(table); + + expect(result).toBeNull(); + }); + + it('Full valid value, return original value', () => { + const tableFormat: TableMetadataFormat = { + topBorderColor: 'red', + bottomBorderColor: 'blue', + verticalBorderColor: 'green', + hasHeaderRow: true, + headerRowColor: 'orange', + hasFirstColumn: true, + hasBandedColumns: false, + hasBandedRows: true, + bgColorEven: 'yellow', + bgColorOdd: 'gray', + tableBorderFormat: TableBorderFormat.Default, + verticalAlign: 'top', + }; + const table: ContentModelTable = { + blockType: 'Table', + format: {}, + rows: [], + widths: [], + dataset: { + editingInfo: JSON.stringify(tableFormat), + }, + }; + const result = getTableMetadata(table); + + expect(result).toEqual({ + topBorderColor: 'red', + bottomBorderColor: 'blue', + verticalBorderColor: 'green', + hasHeaderRow: true, + headerRowColor: 'orange', + hasFirstColumn: true, + hasBandedColumns: false, + hasBandedRows: true, + bgColorEven: 'yellow', + bgColorOdd: 'gray', + tableBorderFormat: TableBorderFormat.Default, + verticalAlign: 'top', + }); + }); +}); describe('updateTableMetadata', () => { it('No value', () => { diff --git a/packages/roosterjs-content-model-dom/test/modelApi/selection/collectSelectionsTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/selection/collectSelectionsTest.ts index 1a3b5c23b47..51538c7552d 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/selection/collectSelectionsTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/selection/collectSelectionsTest.ts @@ -147,10 +147,7 @@ describe('getSelectedSegmentsAndParagraphs', () => { ], true, false, - [ - [s3, null, []], - [s4, null, []], - ] + [] ); }); diff --git a/packages/roosterjs-content-model-dom/test/modelApi/selection/getSelectedSegmentsTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/selection/getSelectedSegmentsTest.ts index e2fa50eeb64..aea8c2ee375 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/selection/getSelectedSegmentsTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/selection/getSelectedSegmentsTest.ts @@ -7,8 +7,10 @@ import { TableSelectionContext, } from 'roosterjs-content-model-types'; import { + createContentModelDocument, createDivider, createEntity, + createListItem, createParagraph, createSelectionMarker, createText, @@ -52,6 +54,9 @@ describe('getSelectedSegments', () => { const p1 = createParagraph(); const p2 = createParagraph(); + p1.segments.push(s1, s2); + p2.segments.push(s3, s4); + runTest( [ { @@ -100,21 +105,46 @@ describe('getSelectedSegments', () => { const s3 = createText('test3'); const s4 = createText('test4'); const b1 = createDivider('div'); + const doc = createContentModelDocument(); runTest( [ { - path: [], + path: [doc], block: b1, segments: [s1, s2], }, { - path: [], + path: [doc], segments: [s3, s4], }, ], true, - [s3, s4] + [] + ); + }); + + it('Block with list item, include format holder', () => { + const s1 = createText('test1'); + const s2 = createText('test2'); + const b1 = createDivider('div'); + const doc = createContentModelDocument(); + const listItem = createListItem([]); + + runTest( + [ + { + path: [doc], + block: b1, + segments: [s1, s2], + }, + { + path: [listItem, doc], + segments: [listItem.formatHolder], + }, + ], + true, + [listItem.formatHolder] ); }); diff --git a/packages/roosterjs-content-model-dom/test/modelApi/selection/iterateSelectionsTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/selection/iterateSelectionsTest.ts index 55f2664bc5d..f1761b764a3 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/selection/iterateSelectionsTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/selection/iterateSelectionsTest.ts @@ -1219,6 +1219,10 @@ describe('iterateSelections', () => { const marker2 = createSelectionMarker(); const cache = 'CACHE' as any; + addSegment(quote1, marker1); + para1.segments.push(marker2); + divider1.isSelected = true; + quote1.cachedElement = cache; para1.cachedElement = cache; divider1.cachedElement = cache; @@ -1226,10 +1230,6 @@ describe('iterateSelections', () => { para2.cachedElement = cache; divider2.cachedElement = cache; - addSegment(quote1, marker1); - para1.segments.push(marker2); - divider1.isSelected = true; - const doc = createContentModelDocument(); doc.blocks.push(quote1, quote2, para1, para2, divider1, divider2); diff --git a/packages/roosterjs-content-model-types/lib/index.ts b/packages/roosterjs-content-model-types/lib/index.ts index 9f696e2c23b..e20fc283675 100644 --- a/packages/roosterjs-content-model-types/lib/index.ts +++ b/packages/roosterjs-content-model-types/lib/index.ts @@ -247,7 +247,10 @@ export { DOMInsertPoint, } from './selection/DOMSelection'; export { InsertPoint } from './selection/InsertPoint'; -export { TableSelectionContext } from './selection/TableSelectionContext'; +export { + TableSelectionContext, + ReadonlyTableSelectionContext, +} from './selection/TableSelectionContext'; export { TableSelectionCoordinates } from './selection/TableSelectionCoordinates'; export { @@ -420,10 +423,11 @@ export { MergeModelOption } from './parameter/MergeModelOption'; export { IterateSelectionsCallback, IterateSelectionsOption, + ReadonlyIterateSelectionsCallback, } from './parameter/IterateSelectionsOption'; export { NodeTypeMap } from './parameter/NodeTypeMap'; export { TypeOfBlockGroup } from './parameter/TypeOfBlockGroup'; -export { OperationalBlocks } from './parameter/OperationalBlocks'; +export { OperationalBlocks, ReadonlyOperationalBlocks } from './parameter/OperationalBlocks'; export { ParsedTable, ParsedTableCell } from './parameter/ParsedTable'; export { ModelToTextCallback, diff --git a/packages/roosterjs-content-model-types/lib/parameter/IterateSelectionsOption.ts b/packages/roosterjs-content-model-types/lib/parameter/IterateSelectionsOption.ts index 7cce60f6fba..b2b010dfd96 100644 --- a/packages/roosterjs-content-model-types/lib/parameter/IterateSelectionsOption.ts +++ b/packages/roosterjs-content-model-types/lib/parameter/IterateSelectionsOption.ts @@ -1,7 +1,19 @@ -import type { ContentModelBlock } from '../contentModel/block/ContentModelBlock'; -import type { ContentModelBlockGroup } from '../contentModel/blockGroup/ContentModelBlockGroup'; -import type { ContentModelSegment } from '../contentModel/segment/ContentModelSegment'; -import type { TableSelectionContext } from '../selection/TableSelectionContext'; +import type { + ContentModelBlock, + ReadonlyContentModelBlock, +} from '../contentModel/block/ContentModelBlock'; +import type { + ContentModelBlockGroup, + ReadonlyContentModelBlockGroup, +} from '../contentModel/blockGroup/ContentModelBlockGroup'; +import type { + ContentModelSegment, + ReadonlyContentModelSegment, +} from '../contentModel/segment/ContentModelSegment'; +import type { + ReadonlyTableSelectionContext, + TableSelectionContext, +} from '../selection/TableSelectionContext'; /** * Options for iterateSelections API @@ -51,3 +63,18 @@ export type IterateSelectionsCallback = ( block?: ContentModelBlock, segments?: ContentModelSegment[] ) => void | boolean; + +/** + * The callback function type for iterateSelections (Readonly) + * @param path The block group path of current selection + * @param tableContext Table context of current selection + * @param block Block of current selection + * @param segments Segments of current selection + * @returns True to stop iterating, otherwise keep going + */ +export type ReadonlyIterateSelectionsCallback = ( + path: ReadonlyContentModelBlockGroup[], + tableContext?: ReadonlyTableSelectionContext, + block?: ReadonlyContentModelBlock, + segments?: ReadonlyContentModelSegment[] +) => void | boolean; diff --git a/packages/roosterjs-content-model-types/lib/parameter/OperationalBlocks.ts b/packages/roosterjs-content-model-types/lib/parameter/OperationalBlocks.ts index b83e3e515d8..ca69ff44ac6 100644 --- a/packages/roosterjs-content-model-types/lib/parameter/OperationalBlocks.ts +++ b/packages/roosterjs-content-model-types/lib/parameter/OperationalBlocks.ts @@ -1,5 +1,11 @@ -import type { ContentModelBlock } from '../contentModel/block/ContentModelBlock'; -import type { ContentModelBlockGroup } from '../contentModel/blockGroup/ContentModelBlockGroup'; +import type { + ContentModelBlock, + ReadonlyContentModelBlock, +} from '../contentModel/block/ContentModelBlock'; +import type { + ContentModelBlockGroup, + ReadonlyContentModelBlockGroup, +} from '../contentModel/blockGroup/ContentModelBlockGroup'; /** * Represent a pair of parent block group and child block @@ -20,3 +26,23 @@ export type OperationalBlocks = { */ path: ContentModelBlockGroup[]; }; + +/** + * Represent a pair of parent block group and child block (Readonly) + */ +export type ReadonlyOperationalBlocks = { + /** + * The parent block group + */ + parent: ReadonlyContentModelBlockGroup; + + /** + * The child block + */ + block: ReadonlyContentModelBlock | T; + + /** + * Selection path of this block + */ + path: ReadonlyContentModelBlockGroup[]; +}; diff --git a/packages/roosterjs-content-model-types/lib/parameter/TypeOfBlockGroup.ts b/packages/roosterjs-content-model-types/lib/parameter/TypeOfBlockGroup.ts index 5cc421f7ce3..75099cce0a9 100644 --- a/packages/roosterjs-content-model-types/lib/parameter/TypeOfBlockGroup.ts +++ b/packages/roosterjs-content-model-types/lib/parameter/TypeOfBlockGroup.ts @@ -1,9 +1,17 @@ -import type { ContentModelBlockGroup } from '../contentModel/blockGroup/ContentModelBlockGroup'; -import type { ContentModelBlockGroupBase } from '../contentModel/blockGroup/ContentModelBlockGroupBase'; +import type { + ContentModelBlockGroup, + ReadonlyContentModelBlockGroup, +} from '../contentModel/blockGroup/ContentModelBlockGroup'; +import type { + ContentModelBlockGroupBase, + ReadonlyContentModelBlockGroupBase, +} from '../contentModel/blockGroup/ContentModelBlockGroupBase'; /** * Retrieve block group type string from a given block group */ export type TypeOfBlockGroup< - T extends ContentModelBlockGroup -> = T extends ContentModelBlockGroupBase ? U : never; + T extends ContentModelBlockGroup | ReadonlyContentModelBlockGroup +> = T extends ContentModelBlockGroupBase | ReadonlyContentModelBlockGroupBase + ? U + : never; diff --git a/packages/roosterjs-content-model-types/lib/selection/TableSelectionContext.ts b/packages/roosterjs-content-model-types/lib/selection/TableSelectionContext.ts index 50d85d6f108..25cd46f5f0a 100644 --- a/packages/roosterjs-content-model-types/lib/selection/TableSelectionContext.ts +++ b/packages/roosterjs-content-model-types/lib/selection/TableSelectionContext.ts @@ -1,4 +1,7 @@ -import type { ContentModelTable } from '../contentModel/block/ContentModelTable'; +import type { + ContentModelTable, + ReadonlyContentModelTable, +} from '../contentModel/block/ContentModelTable'; /** * Context object for table in a selection @@ -24,3 +27,28 @@ export interface TableSelectionContext { */ isWholeTableSelected: boolean; } + +/** + * Context object for table in a selection (Readonly) + */ +export interface ReadonlyTableSelectionContext { + /** + * The table that contains the selection + */ + table: ReadonlyContentModelTable; + + /** + * Row Index of the selected table cell + */ + rowIndex: number; + + /** + * Column Index of the selected table cell + */ + colIndex: number; + + /** + * Whether the whole table is selected + */ + isWholeTableSelected: boolean; +} From ecdb47801f9c851e4780973c10d9823ffe0c93a2 Mon Sep 17 00:00:00 2001 From: Jiuqing Song Date: Wed, 22 May 2024 09:56:34 -0700 Subject: [PATCH 7/7] Content Model Cache improvement - Step 3: Let creators accept readonly types (#2642) * Readonly types (3rd try * Improve * fix build * Improve * improve * Improve * Add shallow mutable type * improve * Improve * improve * improve * add test * Readonly types step 3 * improve * improve * improve --- .../roosterjs-content-model-dom/lib/index.ts | 1 + .../lib/modelApi/common/addDecorators.ts | 21 +++++++++++++------ .../lib/modelApi/creators/createBr.ts | 4 ++-- .../creators/createContentModelDocument.ts | 2 +- .../lib/modelApi/creators/createDivider.ts | 4 ++-- .../lib/modelApi/creators/createEmptyModel.ts | 4 +++- .../lib/modelApi/creators/createEntity.ts | 2 +- .../creators/createFormatContainer.ts | 4 ++-- .../modelApi/creators/createGeneralSegment.ts | 4 ++-- .../lib/modelApi/creators/createImage.ts | 7 +++++-- .../lib/modelApi/creators/createListItem.ts | 6 +++--- .../lib/modelApi/creators/createListLevel.ts | 6 +++--- .../lib/modelApi/creators/createParagraph.ts | 10 ++++----- .../creators/createParagraphDecorator.ts | 4 ++-- .../creators/createSelectionMarker.ts | 4 ++-- .../lib/modelApi/creators/createTable.ts | 14 ++++++------- .../lib/modelApi/creators/createTableCell.ts | 8 +++---- .../lib/modelApi/creators/createTableRow.ts | 16 ++++++++++++++ .../lib/modelApi/creators/createText.ts | 12 +++++------ .../test/modelApi/creators/creatorsTest.ts | 21 +++++++++++++++++++ 20 files changed, 103 insertions(+), 51 deletions(-) create mode 100644 packages/roosterjs-content-model-dom/lib/modelApi/creators/createTableRow.ts diff --git a/packages/roosterjs-content-model-dom/lib/index.ts b/packages/roosterjs-content-model-dom/lib/index.ts index 519aa52801b..202b32ddc95 100644 --- a/packages/roosterjs-content-model-dom/lib/index.ts +++ b/packages/roosterjs-content-model-dom/lib/index.ts @@ -54,6 +54,7 @@ export { createEntity } from './modelApi/creators/createEntity'; export { createDivider } from './modelApi/creators/createDivider'; export { createListLevel } from './modelApi/creators/createListLevel'; export { createEmptyModel } from './modelApi/creators/createEmptyModel'; +export { createTableRow } from './modelApi/creators/createTableRow'; export { mutateBlock, mutateSegments, mutateSegment } from './modelApi/common/mutate'; export { addBlock } from './modelApi/common/addBlock'; diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/common/addDecorators.ts b/packages/roosterjs-content-model-dom/lib/modelApi/common/addDecorators.ts index 25ba00b0703..6abccd578c9 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/common/addDecorators.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/common/addDecorators.ts @@ -1,14 +1,17 @@ import type { - ContentModelCode, - ContentModelLink, - ContentModelSegment, DomToModelDecoratorContext, + ReadonlyContentModelCode, + ReadonlyContentModelLink, + ShallowMutableContentModelSegment, } from 'roosterjs-content-model-types'; /** * @internal */ -export function addLink(segment: ContentModelSegment, link: ContentModelLink) { +export function addLink( + segment: ShallowMutableContentModelSegment, + link: ReadonlyContentModelLink +) { if (link.format.href) { segment.link = { format: { ...link.format }, @@ -22,7 +25,10 @@ export function addLink(segment: ContentModelSegment, link: ContentModelLink) { * @param segment The segment to add decorator to * @param code The code decorator to add */ -export function addCode(segment: ContentModelSegment, code: ContentModelCode) { +export function addCode( + segment: ShallowMutableContentModelSegment, + code: ReadonlyContentModelCode +) { if (code.format.fontFamily) { segment.code = { format: { ...code.format }, @@ -33,7 +39,10 @@ export function addCode(segment: ContentModelSegment, code: ContentModelCode) { /** * @internal */ -export function addDecorators(segment: ContentModelSegment, context: DomToModelDecoratorContext) { +export function addDecorators( + segment: ShallowMutableContentModelSegment, + context: DomToModelDecoratorContext +) { addLink(segment, context.link); addCode(segment, context.code); } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createBr.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createBr.ts index f5c907211b7..55e53d373ce 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createBr.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createBr.ts @@ -4,9 +4,9 @@ import type { ContentModelBr, ContentModelSegmentFormat } from 'roosterjs-conten * Create a ContentModelBr model * @param format @optional The format of this model */ -export function createBr(format?: ContentModelSegmentFormat): ContentModelBr { +export function createBr(format?: Readonly): ContentModelBr { return { segmentType: 'Br', - format: format ? { ...format } : {}, + format: { ...format }, }; } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createContentModelDocument.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createContentModelDocument.ts index d4ef4a4d539..ea30b78b8ba 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createContentModelDocument.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createContentModelDocument.ts @@ -8,7 +8,7 @@ import type { * @param defaultFormat @optional Default format of this model */ export function createContentModelDocument( - defaultFormat?: ContentModelSegmentFormat + defaultFormat?: Readonly ): ContentModelDocument { const result: ContentModelDocument = { blockGroupType: 'Document', diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createDivider.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createDivider.ts index f6d058dd4ea..bd0a27d6342 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createDivider.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createDivider.ts @@ -7,11 +7,11 @@ import type { ContentModelBlockFormat, ContentModelDivider } from 'roosterjs-con */ export function createDivider( tagName: 'hr' | 'div', - format?: ContentModelBlockFormat + format?: Readonly ): ContentModelDivider { return { blockType: 'Divider', tagName, - format: format ? { ...format } : {}, + format: { ...format }, }; } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createEmptyModel.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createEmptyModel.ts index 23c3e2c439a..d255f33d1c5 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createEmptyModel.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createEmptyModel.ts @@ -11,7 +11,9 @@ import type { * Create an empty Content Model Document with initial empty line and insert point with default format * @param format @optional The default format to be applied to this Content Model */ -export function createEmptyModel(format?: ContentModelSegmentFormat): ContentModelDocument { +export function createEmptyModel( + format?: Readonly +): ContentModelDocument { const model = createContentModelDocument(format); const paragraph = createParagraph(false /*isImplicit*/, undefined /*blockFormat*/, format); diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createEntity.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createEntity.ts index da66859a67b..b323e5a4f97 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createEntity.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createEntity.ts @@ -11,7 +11,7 @@ import type { ContentModelEntity, ContentModelSegmentFormat } from 'roosterjs-co export function createEntity( wrapper: HTMLElement, isReadonly: boolean = true, - segmentFormat?: ContentModelSegmentFormat, + segmentFormat?: Readonly, type?: string, id?: string ): ContentModelEntity { diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createFormatContainer.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createFormatContainer.ts index 9bf73a25b2c..bc4d7962ea3 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createFormatContainer.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createFormatContainer.ts @@ -10,13 +10,13 @@ import type { */ export function createFormatContainer( tag: Lowercase, - format?: ContentModelFormatContainerFormat + format?: Readonly ): ContentModelFormatContainer { return { blockType: 'BlockGroup', blockGroupType: 'FormatContainer', tagName: tag, blocks: [], - format: { ...(format || {}) }, + format: { ...format }, }; } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createGeneralSegment.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createGeneralSegment.ts index e92400efd87..b21c253ab96 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createGeneralSegment.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createGeneralSegment.ts @@ -10,13 +10,13 @@ import type { */ export function createGeneralSegment( element: HTMLElement, - format?: ContentModelSegmentFormat + format?: Readonly ): ContentModelGeneralSegment { return { blockType: 'BlockGroup', blockGroupType: 'General', segmentType: 'General', - format: format ? { ...format } : {}, + format: { ...format }, blocks: [], element: element, }; diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createImage.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createImage.ts index 44c3d744d6d..1114ce41b67 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createImage.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createImage.ts @@ -5,11 +5,14 @@ import type { ContentModelImage, ContentModelImageFormat } from 'roosterjs-conte * @param src Image source * @param format @optional The format of this model */ -export function createImage(src: string, format?: ContentModelImageFormat): ContentModelImage { +export function createImage( + src: string, + format?: Readonly +): ContentModelImage { return { segmentType: 'Image', src: src, - format: format ? { ...format } : {}, + format: { ...format }, dataset: {}, }; } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createListItem.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createListItem.ts index fbad6b221de..bbfec49ca13 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createListItem.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createListItem.ts @@ -2,8 +2,8 @@ import { createListLevel } from './createListLevel'; import { createSelectionMarker } from './createSelectionMarker'; import type { ContentModelListItem, - ContentModelListLevel, ContentModelSegmentFormat, + ReadonlyContentModelListLevel, } from 'roosterjs-content-model-types'; /** @@ -12,8 +12,8 @@ import type { * @param format @optional The format of this model */ export function createListItem( - levels: ContentModelListLevel[], - format?: ContentModelSegmentFormat + levels: ReadonlyArray, + format?: Readonly ): ContentModelListItem { const formatHolder = createSelectionMarker(format); diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createListLevel.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createListLevel.ts index 4355b02171c..25b8eb3946e 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createListLevel.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createListLevel.ts @@ -1,7 +1,7 @@ import type { ContentModelListItemLevelFormat, ContentModelListLevel, - DatasetFormat, + ReadonlyDatasetFormat, } from 'roosterjs-content-model-types'; /** @@ -12,8 +12,8 @@ import type { */ export function createListLevel( listType: 'OL' | 'UL', - format?: ContentModelListItemLevelFormat, - dataset?: DatasetFormat + format?: Readonly, + dataset?: ReadonlyDatasetFormat ): ContentModelListLevel { return { listType, diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createParagraph.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createParagraph.ts index 06e3226eecd..f987bc2d66c 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createParagraph.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createParagraph.ts @@ -1,8 +1,8 @@ import type { ContentModelBlockFormat, ContentModelParagraph, - ContentModelParagraphDecorator, ContentModelSegmentFormat, + ReadonlyContentModelParagraphDecorator, } from 'roosterjs-content-model-types'; /** @@ -14,14 +14,14 @@ import type { */ export function createParagraph( isImplicit?: boolean, - blockFormat?: ContentModelBlockFormat, - segmentFormat?: ContentModelSegmentFormat, - decorator?: ContentModelParagraphDecorator + blockFormat?: Readonly, + segmentFormat?: Readonly, + decorator?: ReadonlyContentModelParagraphDecorator ): ContentModelParagraph { const result: ContentModelParagraph = { blockType: 'Paragraph', segments: [], - format: blockFormat ? { ...blockFormat } : {}, + format: { ...blockFormat }, }; if (segmentFormat && Object.keys(segmentFormat).length > 0) { diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createParagraphDecorator.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createParagraphDecorator.ts index fb5e5835ed6..cb924ee780d 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createParagraphDecorator.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createParagraphDecorator.ts @@ -10,10 +10,10 @@ import type { */ export function createParagraphDecorator( tagName: string, - format?: ContentModelSegmentFormat + format?: Readonly ): ContentModelParagraphDecorator { return { tagName: tagName.toLocaleLowerCase(), - format: { ...(format || {}) }, + format: { ...format }, }; } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createSelectionMarker.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createSelectionMarker.ts index 88f5ac2e86a..e8ec164d896 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createSelectionMarker.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createSelectionMarker.ts @@ -8,11 +8,11 @@ import type { * @param format @optional The format of this model */ export function createSelectionMarker( - format?: ContentModelSegmentFormat + format?: Readonly ): ContentModelSelectionMarker { return { segmentType: 'SelectionMarker', isSelected: true, - format: format ? { ...format } : {}, + format: { ...format }, }; } diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTable.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTable.ts index 7a549dac31f..2d62d7cfb09 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTable.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTable.ts @@ -1,3 +1,4 @@ +import { createTableRow } from './createTableRow'; import type { ContentModelTable, ContentModelTableFormat, @@ -9,21 +10,20 @@ import type { * @param rowCount Count of rows of this table * @param format @optional The format of this model */ -export function createTable(rowCount: number, format?: ContentModelTableFormat): ContentModelTable { +export function createTable( + rowCount: number, + format?: Readonly +): ContentModelTable { const rows: ContentModelTableRow[] = []; for (let i = 0; i < rowCount; i++) { - rows.push({ - height: 0, - format: {}, - cells: [], - }); + rows.push(createTableRow()); } return { blockType: 'Table', rows, - format: { ...(format || {}) }, + format: { ...format }, widths: [], dataset: {}, }; diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTableCell.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTableCell.ts index 79d67f76a16..cfe036d6398 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTableCell.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTableCell.ts @@ -1,7 +1,7 @@ import type { ContentModelTableCell, ContentModelTableCellFormat, - DatasetFormat, + ReadonlyDatasetFormat, } from 'roosterjs-content-model-types'; /** @@ -15,8 +15,8 @@ export function createTableCell( spanLeftOrColSpan?: boolean | number, spanAboveOrRowSpan?: boolean | number, isHeader?: boolean, - format?: ContentModelTableCellFormat, - dataset?: DatasetFormat + format?: Readonly, + dataset?: ReadonlyDatasetFormat ): ContentModelTableCell { const spanLeft = typeof spanLeftOrColSpan === 'number' ? spanLeftOrColSpan > 1 : !!spanLeftOrColSpan; @@ -25,7 +25,7 @@ export function createTableCell( return { blockGroupType: 'TableCell', blocks: [], - format: format ? { ...format } : {}, + format: { ...format }, spanLeft, spanAbove, isHeader: !!isHeader, diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTableRow.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTableRow.ts new file mode 100644 index 00000000000..3e9608b6929 --- /dev/null +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createTableRow.ts @@ -0,0 +1,16 @@ +import type { ContentModelBlockFormat, ContentModelTableRow } from 'roosterjs-content-model-types'; + +/** + * Create a ContentModelTableRow model + * @param format @optional The format of this model + */ +export function createTableRow( + format?: Readonly, + height: number = 0 +): ContentModelTableRow { + return { + height: height, + format: { ...format }, + cells: [], + }; +} diff --git a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createText.ts b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createText.ts index 6f73d09c662..c837d11f5c9 100644 --- a/packages/roosterjs-content-model-dom/lib/modelApi/creators/createText.ts +++ b/packages/roosterjs-content-model-dom/lib/modelApi/creators/createText.ts @@ -1,9 +1,9 @@ import { addCode, addLink } from '../common/addDecorators'; import type { - ContentModelCode, - ContentModelLink, ContentModelSegmentFormat, ContentModelText, + ReadonlyContentModelCode, + ReadonlyContentModelLink, } from 'roosterjs-content-model-types'; /** @@ -15,14 +15,14 @@ import type { */ export function createText( text: string, - format?: ContentModelSegmentFormat, - link?: ContentModelLink, - code?: ContentModelCode + format?: Readonly, + link?: ReadonlyContentModelLink, + code?: ReadonlyContentModelCode ): ContentModelText { const result: ContentModelText = { segmentType: 'Text', text: text, - format: format ? { ...format } : {}, + format: { ...format }, }; if (link) { diff --git a/packages/roosterjs-content-model-dom/test/modelApi/creators/creatorsTest.ts b/packages/roosterjs-content-model-dom/test/modelApi/creators/creatorsTest.ts index 019b533068e..c0441215e0e 100644 --- a/packages/roosterjs-content-model-dom/test/modelApi/creators/creatorsTest.ts +++ b/packages/roosterjs-content-model-dom/test/modelApi/creators/creatorsTest.ts @@ -13,6 +13,7 @@ import { createParagraphDecorator } from '../../../lib/modelApi/creators/createP import { createSelectionMarker } from '../../../lib/modelApi/creators/createSelectionMarker'; import { createTable } from '../../../lib/modelApi/creators/createTable'; import { createTableCell } from '../../../lib/modelApi/creators/createTableCell'; +import { createTableRow } from '../../../lib/modelApi/creators/createTableRow'; import { createText } from '../../../lib/modelApi/creators/createText'; import { ContentModelCode, @@ -232,6 +233,26 @@ describe('Creators', () => { }); }); + it('createTableRow', () => { + const row = createTableRow(); + + expect(row).toEqual({ + height: 0, + format: {}, + cells: [], + }); + }); + + it('createTableRow with format', () => { + const row = createTableRow({ direction: 'ltr' }, 100); + + expect(row).toEqual({ + height: 100, + format: { direction: 'ltr' }, + cells: [], + }); + }); + it('createTable', () => { const tableModel = createTable(2);