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

100% Statements 22/22
100% Branches 12/12
50% Functions 1/2
100% Lines 21/21

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 631x 1x                 1x 8x   8x 4x 2x 2x 2x   2x   2x                   2x 1x     2x   2x   2x   2x   2x               2x   1x   1x              
import { iterateSelections, moveChildNodes } from 'roosterjs-content-model-dom';
import { toggleCaret } from '../setDOMSelection/toggleCaret';
import type { SwitchShadowEdit } from 'roosterjs-content-model-types';
 
/**
 * @internal
 * Switch the Shadow Edit mode of editor On/Off
 * @param editorCore The EditorCore object
 * @param isOn True to switch On, False to switch Off
 */
export const switchShadowEdit: SwitchShadowEdit = (editorCore, isOn): void => {
    const core = editorCore;
 
    if (isOn != !!core.lifecycle.shadowEditFragment) {
        if (isOn) {
            const model = !core.cache.cachedModel ? core.api.createContentModel(core) : null;
            const fragment = core.logicalRoot.ownerDocument.createDocumentFragment();
            const clonedRoot = core.logicalRoot.cloneNode(true /*deep*/);
 
            moveChildNodes(fragment, clonedRoot);
 
            core.api.triggerEvent(
                core,
                {
                    eventType: 'enteredShadowEdit',
                },
                false /*broadcast*/
            );
 
            // This need to be done after EnteredShadowEdit event is triggered since EnteredShadowEdit event will cause a SelectionChanged event
            // if current selection is table selection or image selection
            if (!core.cache.cachedModel && model) {
                core.cache.cachedModel = model;
            }
 
            toggleCaret(core, true /* hide */);
 
            core.lifecycle.shadowEditFragment = fragment;
        } else {
            core.lifecycle.shadowEditFragment = null;
 
            toggleCaret(core, false /* hide */);
 
            core.api.triggerEvent(
                core,
                {
                    eventType: 'leavingShadowEdit',
                },
                false /*broadcast*/
            );
 
            if (core.cache.cachedModel) {
                // Force clear cached element from selected block
                iterateSelections(core.cache.cachedModel, () => {});
 
                core.api.setContentModel(core, core.cache.cachedModel, {
                    ignoreSelection: true, // Do not set focus and selection when quit shadow edit, focus may remain in UI control (picker, ...)
                });
            }
        }
    }
};