All files / roosterjs-content-model-core/lib/coreApi/formatContentModel formatContentModel.ts

100% Statements 57/57
97.03% Branches 98/101
100% Functions 7/7
100% Lines 53/53

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 1831x 1x                                       1x           235x 235x 235x 235x               235x   235x 940x   235x 95x   95x   95x 95x   95x 90x   90x     95x 95x   95x               95x   95x 30x     95x                   95x   95x 1x           95x 90x     95x 3x     95x 94x       140x 1x 1x     140x     235x 2x         95x 7x 7x 7x 7x 7x                     235x       235x       235x         39x                             95x       3x             3x              
import { ChangeSource } from 'roosterjs-content-model-dom';
import { scrollCaretIntoView } from './scrollCaretIntoView';
import type {
    ChangedEntity,
    ContentChangedEvent,
    DOMSelection,
    FormatContentModel,
    FormatContentModelContext,
    EditorCore,
} from 'roosterjs-content-model-types';
 
/**
 * @internal
 * The general API to do format change with Content Model
 * It will grab a Content Model for current editor content, and invoke a callback function
 * to do format change. Then according to the return value, write back the modified content model into editor.
 * If there is cached model, it will be used and updated.
 * @param core The EditorCore object
 * @param formatter Formatter function, see ContentModelFormatter
 * @param options More options, see FormatContentModelOptions
 */
export const formatContentModel: FormatContentModel = (
    core,
    formatter,
    options,
    domToModelOptions
) => {
    const { onNodeCreated, rawEvent, selectionOverride, scrollCaretIntoView: scroll } =
        options || {};
    const model = core.api.createContentModel(core, domToModelOptions, selectionOverride);
    const context: FormatContentModelContext = {
        newEntities: [],
        deletedEntities: [],
        rawEvent,
        newImages: [],
        paragraphIndexer: core.cache.paragraphMap,
    };
 
    const hasFocus = core.domHelper.hasFocus();
 
    const changed = formatter(model, context);
    const { skipUndoSnapshot, clearModelCache, entityStates, canUndoByBackspace } = context;
 
    if (changed) {
        const isNested = core.undo.isNested;
        const shouldAddSnapshot =
            (!skipUndoSnapshot || skipUndoSnapshot == 'DoNotSkip') && !isNested;
        const shouldMarkNewContent =
            (skipUndoSnapshot === true || skipUndoSnapshot == 'MarkNewContent') && !isNested;
        let selection: DOMSelection | undefined;
 
        if (shouldAddSnapshot) {
            core.undo.isNested = true;
 
            core.api.addUndoSnapshot(core, !!canUndoByBackspace, entityStates);
        }
 
        try {
            handleImages(core, context);
 
            selection =
                core.api.setContentModel(
                    core,
                    model,
                    hasFocus ? undefined : { ignoreSelection: true }, // If editor did not have focus before format, do not set focus after format
                    onNodeCreated
                ) ?? undefined;
 
            handlePendingFormat(core, context, selection);
 
            if (scroll && (selection?.type == 'range' || selection?.type == 'image')) {
                scrollCaretIntoView(core, selection);
            }
 
            const eventData: ContentChangedEvent = {
                eventType: 'contentChanged',
                contentModel: clearModelCache ? undefined : model,
                selection: clearModelCache ? undefined : selection,
                source: options?.changeSource || ChangeSource.Format,
                data: options?.getChangeData?.(),
                formatApiName: options?.apiName,
                changedEntities: getChangedEntities(context, rawEvent),
            };
 
            core.api.triggerEvent(core, eventData, true /*broadcast*/);
 
            if (canUndoByBackspace && selection?.type == 'range') {
                core.undo.autoCompleteInsertPoint = {
                    node: selection.range.startContainer,
                    offset: selection.range.startOffset,
                };
            }
 
            if (shouldAddSnapshot) {
                core.api.addUndoSnapshot(core, false /*canUndoByBackspace*/, entityStates);
            }
 
            if (shouldMarkNewContent) {
                core.undo.snapshotsManager.hasNewContent = true;
            }
        } finally {
            if (!isNested) {
                core.undo.isNested = false;
            }
        }
    } else {
        if (clearModelCache) {
            core.cache.cachedModel = undefined;
            core.cache.cachedSelection = undefined;
        }
 
        handlePendingFormat(core, context, core.api.getDOMSelection(core));
    }
 
    if (context.announceData) {
        core.api.announce(core, context.announceData);
    }
};
 
function handleImages(core: EditorCore, context: FormatContentModelContext) {
    if (context.newImages.length > 0) {
        const width = core.domHelper.getClientWidth();
        const minMaxImageSize = 10;
        const maxWidth = Math.max(width, minMaxImageSize);
        context.newImages.forEach(image => {
            image.format.maxWidth = `${maxWidth}px`;
        });
    }
}
 
function handlePendingFormat(
    core: EditorCore,
    context: FormatContentModelContext,
    selection?: DOMSelection | null
) {
    const pendingFormat =
        context.newPendingFormat == 'preserve'
            ? core.format.pendingFormat?.format
            : context.newPendingFormat;
    const pendingParagraphFormat =
        context.newPendingParagraphFormat == 'preserve'
            ? core.format.pendingFormat?.paragraphFormat
            : context.newPendingParagraphFormat;
 
    if (
        (pendingFormat || pendingParagraphFormat) &&
        selection?.type == 'range' &&
        selection.range.collapsed
    ) {
        core.format.pendingFormat = {
            format: pendingFormat ? { ...pendingFormat } : undefined,
            paragraphFormat: pendingParagraphFormat ? { ...pendingParagraphFormat } : undefined,
            insertPoint: {
                node: selection.range.startContainer,
                offset: selection.range.startOffset,
            },
        };
    }
}
 
function getChangedEntities(
    context: FormatContentModelContext,
    rawEvent?: Event
): ChangedEntity[] | undefined {
    return context.autoDetectChangedEntities
        ? undefined
        : context.newEntities
              .map(
                  (entity): ChangedEntity => ({
                      entity,
                      operation: 'newEntity',
                      rawEvent,
                  })
              )
              .concat(
                  context.deletedEntities.map(entry => ({
                      entity: entry.entity,
                      operation: entry.operation,
                      rawEvent,
                  }))
              );
}