All files / roosterjs-editor-adapter/lib/corePlugins BridgePlugin.ts

96.7% Statements 88/91
89.74% Branches 70/78
91.3% Functions 21/23
97.59% Lines 81/83

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 2601x 1x 1x 1x 1x                             1x 1x                                                                                     1x 14x             14x 17x 27x   14x   14x   25x   14x 14x 14x 38x             1x               1x 11x 11x 11x 29x   29x 6x               1x 12x 36x   36x   12x     1x 4x     14x 14x   14x   14x 1x   23x     14x 10x                               1x 4x   4x 11x 4x 4x 3x 2x     3x     7x 7x 6x 3x     6x         4x     15x 15x 14x   14x 26x   26x 1x     25x         13x       1x 28x     1x 11x                   1x         24x 14x     24x 2x     1x               11x             1x 11x           38x       89x    
import { cacheGetEventData } from 'roosterjs-content-model-dom';
import { createDarkColorHandler } from '../editor/DarkColorHandlerImpl';
import { createEditPlugin } from './EditPlugin';
import { IgnoredPluginNames } from '../editor/IgnoredPluginNames';
import { newEventToOldEvent, oldEventToNewEvent } from '../editor/utils/eventConverter';
import type {
    EditorPlugin as LegacyEditorPlugin,
    PluginEvent as LegacyPluginEvent,
    ContextMenuProvider as LegacyContextMenuProvider,
    IEditor as ILegacyEditor,
    ExperimentalFeatures,
    SizeTransformer,
    EditPluginState,
    CustomData,
    DarkColorHandler,
} from 'roosterjs-editor-types';
import type { ContextMenuProvider, IEditor, PluginEvent } from 'roosterjs-content-model-types';
import type { MixedPlugin } from '../publicTypes/MixedPlugin';
 
const ExclusivelyHandleEventPluginKey = '__ExclusivelyHandleEventPlugin';
const OldEventKey = '__OldEventFromNewEvent';
 
/**
 * @internal
 * Represents the core data structure of a editor adapter
 */
export interface EditorAdapterCore {
    /**
     * Custom data of this editor
     */
    readonly customData: Record<string, CustomData>;
 
    /**
     * Enabled experimental features
     */
    readonly experimentalFeatures: ExperimentalFeatures[];
 
    /**
     * Dark model handler for the editor, used for variable-based solution.
     * If keep it null, editor will still use original dataset-based dark mode solution.
     */
    readonly darkColorHandler: DarkColorHandler;
 
    /**
     * Plugin state of EditPlugin
     */
    readonly edit: EditPluginState;
 
    /**
     * Context Menu providers
     */
    readonly contextMenuProviders: LegacyContextMenuProvider<any>[];
 
    /**
     * @deprecated Use zoomScale instead
     */
    readonly sizeTransformer: SizeTransformer;
}
 
/**
 * @internal
 * Act as a bridge between Standalone editor and Content Model editor, translate Standalone editor event type to legacy event type
 */
export class BridgePlugin implements ContextMenuProvider<any> {
    private editor: IEditor | null = null;
    private legacyPlugins: LegacyEditorPlugin[];
    private edit: EditPluginState;
    private contextMenuProviders: LegacyContextMenuProvider<any>[];
    private checkExclusivelyHandling: boolean;
 
    constructor(
        private onInitialize: (core: EditorAdapterCore) => ILegacyEditor,
        legacyPlugins: LegacyEditorPlugin[] = [],
        private experimentalFeatures: string[] = []
    ) {
        const editPlugin = createEditPlugin();
 
        this.legacyPlugins = [
            editPlugin,
            ...legacyPlugins.filter(x => !!x && IgnoredPluginNames.indexOf(x.getName()) < 0),
        ];
        this.edit = editPlugin.getState();
        this.contextMenuProviders = this.legacyPlugins.filter(isContextMenuProvider);
        this.checkExclusivelyHandling = this.legacyPlugins.some(
            plugin => plugin.willHandleEventExclusively
        );
    }
 
    /**
     * Get a friendly name of  this plugin
     */
    getName() {
        return 'Bridge';
    }
 
    /**
     * Initialize this plugin. This should only be called from Editor
     * @param editor Editor instance
     */
    initialize(editor: IEditor) {
        const outerEditor = this.onInitialize(this.createEditorCore(editor));
        this.editor = editor;
        this.legacyPlugins.forEach(plugin => {
            plugin.initialize(outerEditor);
 
            if (isMixedPlugin(plugin)) {
                plugin.initializeV9(editor);
            }
        });
    }
 
    /**
     * Dispose this plugin
     */
    dispose() {
        for (let i = this.legacyPlugins.length - 1; i >= 0; i--) {
            const plugin = this.legacyPlugins[i];
 
            plugin.dispose();
        }
        this.editor = null;
    }
 
    willHandleEventExclusively(event: PluginEvent) {
        return this.checkExclusivelyHandling && !!this.cacheGetExclusivelyHandlePlugin(event);
    }
 
    onPluginEvent(event: PluginEvent) {
        const oldEvent = this.cacheGetOldEvent(event);
 
        const exclusivelyHandleEventPlugin = this.cacheGetExclusivelyHandlePlugin(event);
 
        if (exclusivelyHandleEventPlugin) {
            this.handleEvent(exclusivelyHandleEventPlugin, oldEvent, event);
        } else {
            this.legacyPlugins.forEach(plugin => this.handleEvent(plugin, oldEvent, event));
        }
 
        if (oldEvent) {
            Object.assign(
                event,
                oldEventToNewEvent(
                    oldEvent,
                    event,
                    this.editor?.getEnvironment().domToModelSettings
                )
            );
        }
    }
 
    /**
     * A callback to return context menu items
     * @param target Target node that triggered a ContextMenu event
     * @returns An array of context menu items, or null means no items needed
     */
    getContextMenuItems(target: Node, event?: Event): any[] {
        const allItems: any[] = [];
 
        this.contextMenuProviders.forEach(provider => {
            if (isMixedPluginProvider(provider)) {
                const items = provider.getContextMenuItems(target, event) ?? [];
                if (items?.length > 0) {
                    if (allItems.length > 0) {
                        allItems.push(null);
                    }
 
                    allItems.push(...items);
                }
            } else {
                const items = provider.getContextMenuItems(target) ?? [];
                if (items?.length > 0) {
                    if (allItems.length > 0) {
                        allItems.push(null);
                    }
 
                    allItems.push(...items);
                }
            }
        });
 
        return allItems;
    }
 
    private cacheGetExclusivelyHandlePlugin(event: PluginEvent) {
        return cacheGetEventData(event, ExclusivelyHandleEventPluginKey, event => {
            const oldEvent = this.cacheGetOldEvent(event);
 
            for (let i = 0; i < this.legacyPlugins.length; i++) {
                const plugin = this.legacyPlugins[i];
 
                if (oldEvent && plugin.willHandleEventExclusively?.(oldEvent)) {
                    return plugin;
                }
 
                Iif (isMixedPlugin(plugin) && plugin.willHandleEventExclusivelyV9?.(event)) {
                    return plugin;
                }
            }
 
            return null;
        });
    }
 
    private cacheGetOldEvent(event: PluginEvent) {
        return cacheGetEventData(event, OldEventKey, newEventToOldEvent);
    }
 
    private createEditorCore(editor: IEditor): EditorAdapterCore {
        return {
            customData: {},
            experimentalFeatures: (this.experimentalFeatures as ExperimentalFeatures[]) ?? [],
            sizeTransformer: createSizeTransformer(editor),
            darkColorHandler: createDarkColorHandler(editor.getColorManager()),
            edit: this.edit,
            contextMenuProviders: this.contextMenuProviders,
        };
    }
 
    private handleEvent(
        plugin: LegacyEditorPlugin,
        oldEvent: LegacyPluginEvent | undefined,
        newEvent: PluginEvent
    ) {
        if (oldEvent && plugin.onPluginEvent) {
            plugin.onPluginEvent(oldEvent);
        }
 
        if (isMixedPlugin(plugin)) {
            plugin.onPluginEventV9?.(newEvent);
        }
    }
}
 
/**
 * Check if a provider is a V9 context menu provider
 * @param provider The provider to check
 * @returns True if the provider is a V9 context menu provider, false otherwise
 */
function isMixedPluginProvider(provider: any): provider is ContextMenuProvider<any> {
    return isMixedPlugin(provider);
}
 
/**
 * @internal Export for test only. This function is only used for compatibility from older build
 
 */
export function createSizeTransformer(editor: IEditor): SizeTransformer {
    return size => size / editor.getDOMHelper().calculateZoomScale();
}
 
function isContextMenuProvider(
    source: LegacyEditorPlugin
): source is LegacyContextMenuProvider<any> {
    return !!(<LegacyContextMenuProvider<any>>source)?.getContextMenuItems;
}
 
function isMixedPlugin(plugin: LegacyEditorPlugin): plugin is MixedPlugin {
    return !!(plugin as MixedPlugin).initializeV9;
}