All files / roosterjs-content-model-dom/lib/modelApi/editing deleteSelection.ts

100% Statements 19/19
91.67% Branches 11/12
100% Functions 3/3
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 641x 1x 1x                               1x   338x     313x 313x 113x     313x   313x 313x                     1565x   313x               37x 37x   37x 37x     37x 37x      
import { deleteExpandedSelection } from './deleteExpandedSelection';
import { mutateBlock } from '../common/mutate';
import { runEditSteps } from './runEditSteps';
import type {
    DeleteSelectionContext,
    DeleteSelectionResult,
    DeleteSelectionStep,
    FormatContentModelContext,
    ReadonlyContentModelDocument,
} from 'roosterjs-content-model-types';
 
/**
 * Delete selected content from Content Model
 * @param model The model to delete selected content from
 * @param additionalSteps @optional Addition delete steps
 * @param formatContext @optional A context object provided by formatContentModel API
 * @returns A DeleteSelectionResult object to specify the deletion result
 */
export function deleteSelection(
    model: ReadonlyContentModelDocument,
    additionalSteps: (DeleteSelectionStep | null)[] = [],
    formatContext?: FormatContentModelContext
): DeleteSelectionResult {
    const context = deleteExpandedSelection(model, formatContext);
    const steps = additionalSteps.filter(
        (x: DeleteSelectionStep | null): x is DeleteSelectionStep => !!x
    );
 
    runEditSteps(steps, context);
 
    mergeParagraphAfterDelete(context);
    return context;
}
 
// If we end up with multiple paragraphs impacted, we need to merge them
function mergeParagraphAfterDelete(context: DeleteSelectionContext) {
    const {
        insertPoint,
        deleteResult,
        lastParagraph,
        lastTableContext,
        undeletableSegments,
    } = context;
 
    if (
        insertPoint &&
        deleteResult != 'notDeleted' &&
        deleteResult != 'nothingToDelete' &&
        lastParagraph &&
        lastParagraph != insertPoint.paragraph &&
        lastTableContext == insertPoint.tableContext
    ) {
        const mutableLastParagraph = mutateBlock(lastParagraph);
        const mutableInsertingParagraph = mutateBlock(insertPoint.paragraph);
 
        Eif (undeletableSegments) {
            mutableLastParagraph.segments.unshift(...undeletableSegments);
        }
 
        mutableInsertingParagraph.segments.push(...mutableLastParagraph.segments);
        mutableLastParagraph.segments = [];
    }
}