All files / roosterjs-content-model-core/lib/corePlugin/entity EntityPlugin.ts

95.5% Statements 106/111
85.71% Branches 78/91
95% Functions 19/20
95.24% Lines 100/105

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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 2951x 1x                 1x                               1x         1x 121x             121x               1x               1x 121x           1x 75x 75x           1x 115x             1x 394x 394x   4x 4x   69x 69x               106x 106x   2x 2x         1x 8x 4x   4x 3x 4x 2x 2x   2x           175x   175x 175x   175x 33x   11x   22x   11x 11x 9x 9x   9x 9x     9x   9x         9x 2x             2x 2x   2x 2x     2x         175x 2x 1x   1x 1x                   175x     112x 112x   112x 112x 112x     112x 4x   4x 2x   2x         2x     1x     1x   1x 1x               1x                 112x     2x 2x 2x   2x       1x             16x   16x                               1x 9x 9x     9x   9x 10x   10x   10x 9x       9x   1x           1x 121x    
import { findAllEntities } from './findAllEntities';
import {
    createEntity,
    generateEntityClassNames,
    getAllEntityWrappers,
    getObjectKeys,
    isEntityElement,
    parseEntityFormat,
    transformColor,
} from 'roosterjs-content-model-dom';
import {
    handleCompositionEndEvent,
    handleDelimiterContentChangedEvent,
    handleDelimiterKeyDownEvent,
} from './entityDelimiterUtils';
import type {
    ChangedEntity,
    ContentChangedEvent,
    EntityOperation,
    EntityPluginState,
    IEditor,
    MouseUpEvent,
    PluginEvent,
    PluginWithState,
} from 'roosterjs-content-model-types';
 
const ENTITY_ID_REGEX = /_(\d{1,8})$/;
 
/**
 * Entity Plugin helps handle all operations related to an entity and generate entity specified events
 */
class EntityPlugin implements PluginWithState<EntityPluginState> {
    private editor: IEditor | null = null;
    private state: EntityPluginState;
 
    /**
     * Construct a new instance of EntityPlugin
     */
    constructor() {
        this.state = {
            entityMap: {},
        };
    }
 
    /**
     * Get a friendly name of  this plugin
     */
    getName() {
        return 'Entity';
    }
 
    /**
     * Initialize this plugin. This should only be called from Editor
     * @param editor Editor instance
     */
    initialize(editor: IEditor) {
        this.editor = editor;
    }
 
    /**
     * Dispose this plugin
     */
    dispose() {
        this.editor = null;
        this.state.entityMap = {};
    }
 
    /**
     * Get plugin state object
     */
    getState() {
        return this.state;
    }
 
    /**
     * Handle events triggered from editor
     * @param event PluginEvent object
     */
    onPluginEvent(event: PluginEvent) {
        Eif (this.editor) {
            switch (event.eventType) {
                case 'mouseUp':
                    this.handleMouseUpEvent(this.editor, event);
                    break;
                case 'contentChanged':
                    this.handleContentChangedEvent(this.editor, event);
                    break;
                case 'keyDown':
                    handleDelimiterKeyDownEvent(this.editor, event);
                    break;
                case 'compositionEnd':
                    handleCompositionEndEvent(this.editor, event);
                    break;
                case 'editorReady':
                    this.handleContentChangedEvent(this.editor);
                    break;
                case 'extractContentWithDom':
                    this.handleExtractContentWithDomEvent(this.editor, event.clonedRoot);
                    break;
            }
        }
    }
 
    private handleMouseUpEvent(editor: IEditor, event: MouseUpEvent) {
        const { rawEvent, isClicking } = event;
        let node: Node | null = rawEvent.target as Node;
 
        if (isClicking && this.editor) {
            while (node && this.editor.getDOMHelper().isNodeInEditor(node)) {
                if (isEntityElement(node)) {
                    this.triggerEvent(editor, node as HTMLElement, 'click', rawEvent);
                    break;
                } else {
                    node = node.parentNode;
                }
            }
        }
    }
 
    private handleContentChangedEvent(editor: IEditor, event?: ContentChangedEvent) {
        const modifiedEntities: ChangedEntity[] =
            event?.changedEntities ?? this.getChangedEntities(editor);
        const entityStates = event?.entityStates;
 
        modifiedEntities.forEach(entry => {
            const { entity, operation, rawEvent } = entry;
            const {
                entityFormat: { id, entityType, isFakeEntity },
                wrapper,
            } = entity;
 
            Eif (entityType && !isFakeEntity) {
                if (operation == 'newEntity') {
                    entity.entityFormat.id = this.ensureUniqueId(entityType, id ?? '', wrapper);
                    wrapper.className = generateEntityClassNames(entity.entityFormat);
 
                    Eif (entity.entityFormat.isReadonly) {
                        wrapper.contentEditable = 'false';
                    }
 
                    const eventResult = this.triggerEvent(editor, wrapper, operation, rawEvent);
 
                    this.state.entityMap[entity.entityFormat.id] = {
                        element: wrapper,
                        canPersist: eventResult?.shouldPersist,
                    };
 
                    if (editor.isDarkMode()) {
                        transformColor(
                            wrapper,
                            true /*includeSelf*/,
                            'lightToDark',
                            editor.getColorManager()
                        );
                    }
                } else Eif (id) {
                    const mapEntry = this.state.entityMap[id];
 
                    Eif (mapEntry) {
                        mapEntry.isDeleted = true;
                    }
 
                    this.triggerEvent(editor, wrapper, operation, rawEvent);
                }
            }
        });
 
        entityStates?.forEach(entityState => {
            const { id, state } = entityState;
            const wrapper = this.state.entityMap[id]?.element;
 
            Eif (wrapper) {
                this.triggerEvent(
                    editor,
                    wrapper,
                    'updateEntityState',
                    undefined /*rawEvent*/,
                    state
                );
            }
        });
 
        handleDelimiterContentChangedEvent(editor);
    }
 
    private getChangedEntities(editor: IEditor): ChangedEntity[] {
        const result: ChangedEntity[] = [];
 
        editor.formatContentModel(model => {
            findAllEntities(model, result);
            return false;
        });
 
        getObjectKeys(this.state.entityMap).forEach(id => {
            const entry = this.state.entityMap[id];
 
            if (!entry.isDeleted) {
                const index = result.findIndex(
                    x =>
                        x.operation == 'newEntity' &&
                        x.entity.entityFormat.id == id &&
                        x.entity.wrapper == entry.element
                );
 
                if (index >= 0) {
                    // Found matched entity in editor, so there is no change to this entity,
                    // we can safely remove it from the new entity array
                    result.splice(index, 1);
                } else {
                    // Entity is not in editor, which means it is deleted, use a temporary entity here to represent this entity
                    const format = parseEntityFormat(entry.element);
 
                    Eif (!format.isFakeEntity) {
                        const entity = createEntity(
                            entry.element,
                            format.isReadonly,
                            {},
                            format.entityType,
                            format.id
                        );
 
                        result.push({
                            entity: entity,
                            operation: 'overwrite',
                        });
                    }
                }
            }
        });
 
        return result;
    }
 
    private handleExtractContentWithDomEvent(editor: IEditor, root: HTMLElement) {
        getAllEntityWrappers(root).forEach(element => {
            element.removeAttribute('contentEditable');
 
            this.triggerEvent(editor, element, 'replaceTemporaryContent');
        });
    }
 
    private triggerEvent(
        editor: IEditor,
        wrapper: HTMLElement,
        operation: EntityOperation,
        rawEvent?: Event,
        state?: string
    ) {
        const format = parseEntityFormat(wrapper);
 
        return format.id && format.entityType && !format.isFakeEntity
            ? editor.triggerEvent('entityOperation', {
                  operation: operation,
                  rawEvent,
                  entity: {
                      id: format.id,
                      type: format.entityType,
                      isReadonly: !!format.isReadonly,
                      wrapper,
                  },
                  state: operation == 'updateEntityState' ? state : undefined,
                  shouldPersist: operation == 'newEntity' ? true : undefined, // By default, we always persist entity now
              })
            : null;
    }
 
    private ensureUniqueId(type: string, id: string, wrapper: HTMLElement): string {
        const match = ENTITY_ID_REGEX.exec(id);
        const baseId = (match ? id.substr(0, id.length - match[0].length) : id) || type;
 
        // Make sure entity id is unique
        let newId = '';
 
        for (let num = (match && parseInt(match[1])) || 0; ; num++) {
            newId = num > 0 ? `${baseId}_${num}` : baseId;
 
            const item = this.state.entityMap[newId];
 
            if (!item || item.element == wrapper) {
                break;
            }
        }
 
        return newId;
    }
}
 
/**
 * @internal
 * Create a new instance of EntityPlugin.
 */
export function createEntityPlugin(): PluginWithState<EntityPluginState> {
    return new EntityPlugin();
}