All files / roosterjs-content-model-api/lib/publicApi/utils formatSegmentWithContentModel.ts

97.4% Statements 75/77
80% Branches 24/30
100% Functions 14/14
96.61% Lines 57/59

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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 2171x 1x                                                           1x                                 172x   172x             172x 133x     172x 14x 14x   14x     14x   14x                   172x         172x   172x 165x 2x   163x           172x 54x 54x         172x 164x       172x     172x 164x 164x         172x       172x 14x 14x 14x   158x                   2x 2x                     2x       2x                         2x   2x 2x 2x           2x   2x 1x 1x 1x     1x   1x 1x             1x 1x     1x                   172x 1x 1x   1x      
import { adjustWordSelection } from '../../modelApi/selection/adjustWordSelection';
import {
    contentModelToDom,
    createDomToModelContext,
    createModelToDomContext,
    domToContentModel,
    getSelectedSegmentsAndParagraphs,
    mergeTextSegments,
} from 'roosterjs-content-model-dom';
import type {
    ContentModelDocument,
    ContentModelEntity,
    ContentModelSegmentFormat,
    EditorContext,
    FormattableRoot,
    IEditor,
    PluginEventData,
    ReadonlyContentModelDocument,
    ShallowMutableContentModelParagraph,
    ShallowMutableContentModelSegment,
} from 'roosterjs-content-model-types';
 
/**
 * Invoke a callback to format the selected segment using Content Model
 * @param editor The editor object
 * @param apiName Name of API this calling this function. This is mostly for logging.
 * @param toggleStyleCallback The callback to format the segment. It will be called with current selected table. If no table is selected, it will not be called.
 * @param segmentHasStyleCallback The callback used for checking if the given segment already has required format
 * @param includingFormatHolder True to also include format holder of list item when search selected segments
 * @param afterFormatCallback A callback to invoke after format is applied to all selected segments and before the change is applied to DOM tree
 */
export function formatSegmentWithContentModel(
    editor: IEditor,
    apiName: string,
    toggleStyleCallback: (
        format: ContentModelSegmentFormat,
        isTuringOn: boolean,
        segment: ShallowMutableContentModelSegment | null,
        paragraph: ShallowMutableContentModelParagraph | null
    ) => void,
    segmentHasStyleCallback?: (
        format: ContentModelSegmentFormat,
        segment: ShallowMutableContentModelSegment | null,
        paragraph: ShallowMutableContentModelParagraph | null
    ) => boolean,
    includingFormatHolder?: boolean,
    afterFormatCallback?: (model: ReadonlyContentModelDocument) => void
) {
    editor.formatContentModel(
        (model, context) => {
            let segmentAndParagraphs = getSelectedSegmentsAndParagraphs(
                model,
                !!includingFormatHolder,
                true /*includingEntity*/,
                true /*mutate*/
            );
            let isCollapsedSelection =
                segmentAndParagraphs.length >= 1 &&
                segmentAndParagraphs.every(x => x[0].segmentType == 'SelectionMarker');
 
            // 1. adjust selection to a word if selection is collapsed
            if (isCollapsedSelection) {
                const para = segmentAndParagraphs[0][1];
                const path = segmentAndParagraphs[0][2];
 
                segmentAndParagraphs = adjustWordSelection(
                    model,
                    segmentAndParagraphs[0][0]
                ).map(x => [x, para, path]);
 
                Iif (segmentAndParagraphs.length > 1) {
                    isCollapsedSelection = false;
                }
            }
 
            // 2. expand selection for entities if any
            const formatsAndSegments: [
                ContentModelSegmentFormat,
                ShallowMutableContentModelSegment | null,
                ShallowMutableContentModelParagraph | null
            ][] = [];
            const modelsFromEntities: [
                ContentModelEntity,
                FormattableRoot,
                ContentModelDocument
            ][] = [];
 
            segmentAndParagraphs.forEach(item => {
                if (item[0].segmentType == 'Entity') {
                    expandEntitySelections(editor, item[0], formatsAndSegments, modelsFromEntities);
                } else {
                    formatsAndSegments.push([item[0].format, item[0], item[1]]);
                }
            });
 
            // 3. check if we should turn format on (when not all selection has the required format already)
            // or off (all selections already have the required format)
            const isTurningOff = segmentHasStyleCallback
                ? formatsAndSegments.every(([format, segment, paragraph]) =>
                      segmentHasStyleCallback(format, segment, paragraph)
                  )
                : false;
 
            // 4. invoke the callback function to apply the format
            formatsAndSegments.forEach(([format, segment, paragraph]) => {
                toggleStyleCallback(format, !isTurningOff, segment, paragraph);
            });
 
            // 5. after format is applied to all selections, invoke another callback to do some clean up before write the change back
            afterFormatCallback?.(model);
 
            // 6. finally merge segments if possible, to avoid fragmentation
            formatsAndSegments.forEach(([_, __, paragraph]) => {
                Eif (paragraph) {
                    mergeTextSegments(paragraph);
                }
            });
 
            // 7. Write back models that we got from entities (if any)
            writeBackEntities(editor, modelsFromEntities);
 
            // 8. if the selection is still collapsed, it means we didn't actually applied format, set a pending format so it can be applied when user type
            // otherwise, write back to editor
            if (isCollapsedSelection) {
                context.newPendingFormat = segmentAndParagraphs[0][0].format;
                editor.focus();
                return false;
            } else {
                return formatsAndSegments.length > 0;
            }
        },
        {
            apiName,
        }
    );
}
 
function createEditorContextForEntity(editor: IEditor, entity: ContentModelEntity): EditorContext {
    const domHelper = editor.getDOMHelper();
    const context: EditorContext = {
        isDarkMode: editor.isDarkMode(),
        defaultFormat: { ...entity.format },
        darkColorHandler: editor.getColorManager(),
        addDelimiterForEntity: false,
        allowCacheElement: false,
        domIndexer: undefined,
        zoomScale: domHelper.calculateZoomScale(),
        experimentalFeatures: [],
    };
 
    Iif (editor.getDocument().defaultView?.getComputedStyle(entity.wrapper).direction == 'rtl') {
        context.isRootRtl = true;
    }
 
    return context;
}
 
function expandEntitySelections(
    editor: IEditor,
    entity: ContentModelEntity,
    formatsAndSegments: [
        ContentModelSegmentFormat,
        ShallowMutableContentModelSegment | null,
        ShallowMutableContentModelParagraph | null
    ][],
    modelsFromEntities: [ContentModelEntity, FormattableRoot, ContentModelDocument][]
) {
    const { id, entityType: type, isReadonly } = entity.entityFormat;
 
    Eif (id && type) {
        const formattableRoots: FormattableRoot[] = [];
        const entityOperationEventData: PluginEventData<'entityOperation'> = {
            entity: { id, type, isReadonly: !!isReadonly, wrapper: entity.wrapper },
            operation: 'beforeFormat',
            formattableRoots,
        };
 
        editor.triggerEvent('entityOperation', entityOperationEventData);
 
        formattableRoots.forEach(root => {
            Eif (entity.wrapper.contains(root.element)) {
                const editorContext = createEditorContextForEntity(editor, entity);
                const context = createDomToModelContext(editorContext, root.domToModelOptions);
 
                // Treat everything as selected since the parent entity is selected
                context.isInSelection = true;
 
                const model = domToContentModel(root.element, context);
                const selections = getSelectedSegmentsAndParagraphs(
                    model,
                    false /*includingFormatHolder*/,
                    false /*includingEntity*/,
                    true /*mutate*/
                );
 
                selections.forEach(item => {
                    formatsAndSegments.push([item[0].format, item[0], item[1]]);
                });
 
                modelsFromEntities.push([entity, root, model]);
            }
        });
    }
}
 
function writeBackEntities(
    editor: IEditor,
    modelsFromEntities: [ContentModelEntity, FormattableRoot, ContentModelDocument][]
) {
    modelsFromEntities.forEach(([entity, root, model]) => {
        const editorContext = createEditorContextForEntity(editor, entity);
        const modelToDomContext = createModelToDomContext(editorContext, root.modelToDomOptions);
 
        contentModelToDom(editor.getDocument(), root.element, model, modelToDomContext);
    });
}