All files / roosterjs-content-model-core/lib/corePlugin/format FormatPlugin.ts

96.39% Statements 80/83
82.93% Branches 68/82
92.86% Functions 13/14
96.3% Lines 78/81

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 2381x 1x 1x                                       1x   1x       1x                       1x 118x     118x           118x 118x         118x   118x 472x 25x               1x                   1x 117x               1x 84x           1x 109x                 1x 394x       394x   1x   1x     1x 1x       13x 13x 2x 2x 11x             7x     13x       57x   57x 35x   57x       1x 2x 2x           2x       1x 39x               1x 54x   54x 21x   21x 21x   21x 21x       54x     1x 9x 9x 9x   9x   8x   8x 8x     8x   8x 4x 3x 3x 9x 7x       3x 1x       3x             7x   1x     1x             1x 118x    
import { applyDefaultFormat } from './applyDefaultFormat';
import { applyPendingFormat } from './applyPendingFormat';
import {
    getObjectKeys,
    isBlockElement,
    isCharacterValue,
    isCursorMovingKey,
    isNodeOfType,
} from 'roosterjs-content-model-dom';
import type {
    BackgroundColorFormat,
    FontFamilyFormat,
    FontSizeFormat,
    FormatPluginState,
    IEditor,
    PluginEvent,
    PluginWithState,
    EditorOptions,
    TextColorFormat,
} from 'roosterjs-content-model-types';
 
// During IME input, KeyDown event will have "Process" as key
const ProcessKey = 'Process';
// For some Android IME, KeyDown event will have "Unidentified" as key
const UnidentifiedKey = 'Unidentified';
const DefaultStyleKeyMap: Record<
    keyof (FontFamilyFormat & FontSizeFormat & TextColorFormat & BackgroundColorFormat),
    keyof CSSStyleDeclaration
> = {
    backgroundColor: 'backgroundColor',
    textColor: 'color',
    fontFamily: 'fontFamily',
    fontSize: 'fontSize',
};
 
/**
 * FormatPlugin plugins helps editor to do formatting on top of content model.
 * This includes:
 * 1. Handle pending format changes when selection is collapsed
 */
class FormatPlugin implements PluginWithState<FormatPluginState> {
    private editor: IEditor | null = null;
    private defaultFormatKeys: Set<keyof CSSStyleDeclaration>;
    private state: FormatPluginState;
    private lastCheckedNode: Node | null = null;
 
    /**
     * Construct a new instance of FormatPlugin class
     * @param option The editor option
     */
    constructor(option: EditorOptions) {
        this.state = {
            defaultFormat: { ...option.defaultSegmentFormat },
            pendingFormat: null,
        };
 
        this.defaultFormatKeys = new Set<keyof CSSStyleDeclaration>();
 
        getObjectKeys(DefaultStyleKeyMap).forEach(key => {
            if (this.state.defaultFormat[key]) {
                this.defaultFormatKeys.add(DefaultStyleKeyMap[key]);
            }
        });
    }
 
    /**
     * Get name of this plugin
     */
    getName() {
        return 'Format';
    }
 
    /**
     * The first method that editor will call to a plugin when editor is initializing.
     * It will pass in the editor instance, plugin should take this chance to save the
     * editor reference so that it can call to any editor method or format API later.
     * @param editor The editor object
     */
    initialize(editor: IEditor) {
        this.editor = editor;
    }
 
    /**
     * The last method that editor will call to a plugin before it is disposed.
     * Plugin can take this chance to clear the reference to editor. After this method is
     * called, plugin should not call to any editor method since it will result in error.
     */
    dispose() {
        this.editor = null;
    }
 
    /**
     * Get plugin state object
     */
    getState(): FormatPluginState {
        return this.state;
    }
 
    /**
     * Core method for a plugin. Once an event happens in editor, editor will call this
     * method of each plugin to handle the event as long as the event is not handled
     * exclusively by another plugin.
     * @param event The event to handle:
     */
    onPluginEvent(event: PluginEvent) {
        Iif (!this.editor) {
            return;
        }
 
        switch (event.eventType) {
            case 'input':
                this.checkAndApplyPendingFormat(event.rawEvent.data);
 
                break;
 
            case 'compositionEnd':
                this.checkAndApplyPendingFormat(event.rawEvent.data);
                break;
 
            case 'keyDown':
                const isAndroidIME =
                    this.editor.getEnvironment().isAndroid && event.rawEvent.key == UnidentifiedKey;
                if (isCursorMovingKey(event.rawEvent)) {
                    this.clearPendingFormat();
                    this.lastCheckedNode = null;
                } else if (
                    this.defaultFormatKeys.size > 0 &&
                    (isAndroidIME ||
                        isCharacterValue(event.rawEvent) ||
                        event.rawEvent.key == ProcessKey) &&
                    this.shouldApplyDefaultFormat(this.editor)
                ) {
                    applyDefaultFormat(this.editor, this.state.defaultFormat);
                }
 
                break;
 
            case 'mouseUp':
            case 'contentChanged':
                this.lastCheckedNode = null;
 
                if (!this.canApplyPendingFormat()) {
                    this.clearPendingFormat();
                }
                break;
        }
    }
 
    private checkAndApplyPendingFormat(data: string | null) {
        Eif (this.editor && data && this.state.pendingFormat) {
            applyPendingFormat(
                this.editor,
                data,
                this.state.pendingFormat.format,
                this.state.pendingFormat.paragraphFormat
            );
            this.clearPendingFormat();
        }
    }
 
    private clearPendingFormat() {
        this.state.pendingFormat = null;
    }
 
    /**
     * @internal
     * Check if this editor can apply pending format
     * @param editor The editor to get format from
     */
    private canApplyPendingFormat(): boolean {
        let result = false;
 
        if (this.state.pendingFormat && this.editor) {
            const selection = this.editor.getDOMSelection();
            const range =
                selection?.type == 'range' && selection.range.collapsed ? selection.range : null;
            const { node, offset } = this.state.pendingFormat.insertPoint;
 
            Eif (range && range.startContainer == node && range.startOffset == offset) {
                result = true;
            }
        }
 
        return result;
    }
 
    private shouldApplyDefaultFormat(editor: IEditor): boolean {
        const selection = editor.getDOMSelection();
        const range = selection?.type == 'range' ? selection.range : null;
        const posContainer = range?.startContainer ?? null;
 
        if (posContainer && posContainer != this.lastCheckedNode) {
            // Cache last checked parent node so no need to check it again if user is keep typing under the same node
            this.lastCheckedNode = posContainer;
 
            const domHelper = editor.getDOMHelper();
            let element: HTMLElement | null = isNodeOfType(posContainer, 'ELEMENT_NODE')
                ? posContainer
                : posContainer.parentElement;
            const foundFormatKeys = new Set<keyof CSSStyleDeclaration>();
 
            while (element?.parentElement && domHelper.isNodeInEditor(element.parentElement)) {
                if (element.getAttribute?.('style')) {
                    const style = element.style;
                    this.defaultFormatKeys.forEach(key => {
                        if (style[key]) {
                            foundFormatKeys.add(key);
                        }
                    });
 
                    if (foundFormatKeys.size == this.defaultFormatKeys.size) {
                        return false;
                    }
                }
 
                Eif (isBlockElement(element)) {
                    break;
                }
 
                element = element.parentElement;
            }
 
            return true;
        } else {
            return false;
        }
    }
}
 
/**
 * @internal
 * Create a new instance of FormatPlugin.
 * @param option The editor option
 */
export function createFormatPlugin(option: EditorOptions): PluginWithState<FormatPluginState> {
    return new FormatPlugin(option);
}