All files / roosterjs-content-model-core/lib/corePlugin/copyPaste CopyPastePlugin.ts

86.31% Statements 145/168
73.68% Branches 98/133
90.63% Functions 29/32
86.5% Lines 141/163

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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 3901x 1x 1x 1x 1x 1x 1x                                                             1x         1x 147x 147x   147x           147x 147x                   1x               151x 151x 151x   8x     9x     7x     151x           1x 75x         75x 75x   75x 75x           1x 151x     16x 16x       16x 16x   16x   16x 14x   14x   14x 4x               10x 6x     14x 14x   14x   14x             14x       14x 14x             14x 7x 7x 7x 7x 7x 7x     14x 14x       14x 14x 14x   14x 6x   6x       4x     6x                             147x 8x 8x   8x   8x 8x 8x       8x 7x             1x 14x                                     14x   14x 14x 14x   14x 14x 14x   14x   1x         1x         10x 7x 3x 3x   3x     4x 4x 3x 3x 3x     4x         14x 14x 14x 14x       15x       14x   14x 4x   4x   4x 4x 10x 4x 4x   6x     14x             1x 2x 1x   2x 2x   2x             1x 2x 2x   2x   8x     2x   2x   2x 4x               1x       14x 2x     12x 9x         3x 3x 3x 3x 3x                 1x     147x    
import { addRangeToSelection } from '../../coreApi/setDOMSelection/addRangeToSelection';
import { adjustImageSelectionOnSafari } from './utils/adjustImageSelectionOnSafari';
import { deleteEmptyList } from './utils/deleteEmptyList';
import { onCreateCopyEntityNode } from '../../override/pasteCopyBlockEntityParser';
import { paste } from '../../command/paste/paste';
import { pruneUnselectedModel } from './utils/pruneUnselectedModel';
import {
    ChangeSource,
    contentModelToDom,
    contentModelToText,
    createModelToDomContext,
    deleteSelection,
    extractClipboardItems,
    getSelectedCells,
    isElementOfType,
    isNodeOfType,
    iterateSelections,
    moveChildNodes,
    normalizeContentModel,
    toArray,
    wrap,
} from 'roosterjs-content-model-dom';
import type {
    ClipboardData,
    CopyPastePluginState,
    ContentModelTable,
    DOMSelection,
    IEditor,
    OnNodeCreated,
    EditorOptions,
    PluginWithState,
    ContentModelDocument,
    ContentModelParagraph,
    ContentModelSegment,
    ReadonlyTableSelectionContext,
} from 'roosterjs-content-model-types';
 
const TEMP_DIV_ID = 'roosterJS_copyCutTempDiv';
 
/**
 * Copy and paste plugin for handling onCopy and onPaste event
 */
class CopyPastePlugin implements PluginWithState<CopyPastePluginState> {
    private editor: IEditor | null = null;
    private disposer: (() => void) | null = null;
    private state: CopyPastePluginState;
    private customCopyCutEnabled: boolean = false;
 
    /**
     * Construct a new instance of CopyPastePlugin
     * @param option The editor option
     */
    constructor(option: EditorOptions) {
        this.state = {
            allowedCustomPasteType: option.allowedCustomPasteType || [],
            tempDiv: null,
            defaultPasteType: option.defaultPasteType,
        };
    }
 
    /**
     * Get a friendly name of  this plugin
     */
    getName() {
        return 'CopyPaste';
    }
 
    /**
     * Initialize this plugin. This should only be called from Editor
     * @param editor Editor instance
     */
    initialize(editor: IEditor) {
        this.editor = editor;
        this.disposer = this.editor.attachDomEvent({
            paste: {
                beforeDispatch: e => this.onPaste(e),
            },
            copy: {
                beforeDispatch: e => this.onCutCopy(e, false /*isCut*/),
            },
            cut: {
                beforeDispatch: e => this.onCutCopy(e, true /*isCut*/),
            },
        });
        this.customCopyCutEnabled = editor.isExperimentalFeatureEnabled('CustomCopyCut');
    }
 
    /**
     * Dispose this plugin
     */
    dispose() {
        Iif (this.state.tempDiv) {
            this.state.tempDiv.parentNode?.removeChild(this.state.tempDiv);
            this.state.tempDiv = null;
        }
 
        Eif (this.disposer) {
            this.disposer();
        }
        this.disposer = null;
        this.editor = null;
    }
 
    /**
     * Get plugin state object
     */
    getState() {
        return this.state;
    }
 
    private onCutCopy(event: Event, isCut: boolean) {
        Iif (!this.editor) {
            return;
        }
 
        const doc = this.editor.getDocument();
        const selection = this.editor.getDOMSelection();
 
        adjustImageSelectionOnSafari(this.editor, selection);
 
        if (selection && (selection.type != 'range' || !selection.range.collapsed)) {
            const pasteModel = this.editor.getContentModelCopy('disconnected');
 
            pruneUnselectedModel(pasteModel);
 
            if (selection.type === 'table') {
                iterateSelections(pasteModel, (_, tableContext) => {
                    if (tableContext?.table) {
                        preprocessTable(tableContext.table);
 
                        return true;
                    }
                    return false;
                });
            } else if (selection.type === 'range') {
                adjustSelectionForCopyCut(pasteModel);
            }
 
            const tempDiv = this.getTempDiv(this.editor.getDocument());
            const context = createModelToDomContext();
 
            context.onNodeCreated = onNodeCreated;
 
            const selectionForCopy = contentModelToDom(
                tempDiv.ownerDocument,
                tempDiv,
                pasteModel,
                context
            );
 
            let newRange: Range | null = selectionForCopy
                ? domSelectionToRange(doc, selectionForCopy)
                : null;
 
            Eif (newRange) {
                newRange = this.editor.triggerEvent('beforeCutCopy', {
                    clonedRoot: tempDiv,
                    range: newRange,
                    rawEvent: event as ClipboardEvent,
                    isCut,
                }).range;
 
                if (this.customCopyCutEnabled && isClipboardEvent(event)) {
                    event.preventDefault();
                    const text = contentModelToText(pasteModel);
                    event.clipboardData?.setData('text/html', tempDiv.innerHTML);
                    event.clipboardData?.setData('text/plain', text);
                } else Eif (newRange) {
                    addRangeToSelection(doc, newRange);
                }
 
                doc.defaultView?.requestAnimationFrame(() => {
                    Iif (!this.editor) {
                        return;
                    }
 
                    cleanUpAndRestoreSelection(tempDiv);
                    this.editor.setDOMSelection(selection);
                    this.editor.focus();
 
                    if (isCut) {
                        this.editor.formatContentModel(
                            (model, context) => {
                                if (
                                    deleteSelection(model, [deleteEmptyList], context)
                                        .deleteResult == 'range'
                                ) {
                                    normalizeContentModel(model);
                                }
 
                                return true;
                            },
                            {
                                apiName: 'cut',
                                changeSource: ChangeSource.Cut,
                            }
                        );
                    }
                });
            } else {
                cleanUpAndRestoreSelection(tempDiv);
            }
        }
    }
 
    private onPaste = (event: Event) => {
        Eif (this.editor && isClipboardEvent(event)) {
            const editor = this.editor;
 
            const dataTransfer = event.clipboardData;
 
            Eif (shouldPreventDefaultPaste(dataTransfer, editor)) {
                event.preventDefault();
                extractClipboardItems(
                    toArray(dataTransfer!.items),
                    this.state.allowedCustomPasteType
                ).then((clipboardData: ClipboardData) => {
                    if (!editor.isDisposed()) {
                        paste(editor, clipboardData, this.state.defaultPasteType);
                    }
                });
            }
        }
    };
 
    private getTempDiv(doc: Document) {
        Iif (!this.state.tempDiv) {
            const tempDiv = doc.createElement('div');
 
            tempDiv.style.width = '600px';
            tempDiv.style.height = '1px';
            tempDiv.style.overflow = 'hidden';
            tempDiv.style.position = 'fixed';
            tempDiv.style.top = '0';
            tempDiv.style.left = '0';
            tempDiv.style.userSelect = 'text';
            tempDiv.contentEditable = 'true';
 
            if (!this.customCopyCutEnabled) {
                doc.body.appendChild(tempDiv);
            }
 
            this.state.tempDiv = tempDiv;
        }
 
        const div = this.state.tempDiv;
 
        div.style.backgroundColor = 'white';
        div.style.color = 'black';
        div.childNodes.forEach(node => div.removeChild(node));
 
        div.style.display = '';
        div.id = TEMP_DIV_ID;
        div.focus();
 
        return div;
    }
}
/**
 * @internal
 * Exported only for unit testing
 */
export function adjustSelectionForCopyCut(pasteModel: ContentModelDocument) {
    let selectionMarker: ContentModelSegment | undefined;
    let firstBlock: ContentModelParagraph | undefined;
    let tableContext: ReadonlyTableSelectionContext | undefined;
 
    iterateSelections(pasteModel, (_, tableCtxt, block, segments) => {
        if (selectionMarker) {
            Eif (tableCtxt != tableContext && firstBlock?.segments.includes(selectionMarker)) {
                firstBlock.segments.splice(firstBlock.segments.indexOf(selectionMarker), 1);
            }
            return true;
        }
 
        const marker = segments?.find(segment => segment.segmentType == 'SelectionMarker');
        if (!selectionMarker && marker) {
            tableContext = tableCtxt;
            firstBlock = block?.blockType == 'Paragraph' ? block : undefined;
            selectionMarker = marker;
        }
 
        return false;
    });
}
 
function cleanUpAndRestoreSelection(tempDiv: HTMLDivElement) {
    tempDiv.style.backgroundColor = '';
    tempDiv.style.color = '';
    tempDiv.style.display = 'none';
    moveChildNodes(tempDiv);
}
 
function isClipboardEvent(event: Event): event is ClipboardEvent {
    return !!(event as ClipboardEvent).clipboardData;
}
 
function domSelectionToRange(doc: Document, selection: DOMSelection): Range | null {
    let newRange: Range | null = null;
 
    if (selection.type === 'table') {
        const table = selection.table;
        const elementToSelect =
            table.parentElement?.childElementCount == 1 ? table.parentElement : table;
 
        newRange = doc.createRange();
        newRange.selectNode(elementToSelect);
    } else if (selection.type === 'image') {
        newRange = doc.createRange();
        newRange.selectNode(selection.image);
    } else {
        newRange = selection.range;
    }
 
    return newRange;
}
 
/**
 * @internal
 * Exported only for unit testing
 */
export const onNodeCreated: OnNodeCreated = (modelElement, node): void => {
    if (isNodeOfType(node, 'ELEMENT_NODE') && isElementOfType(node, 'table')) {
        wrap(node.ownerDocument, node, 'div');
    }
    Eif (isNodeOfType(node, 'ELEMENT_NODE') && !node.isContentEditable) {
        node.removeAttribute('contenteditable');
    }
    onCreateCopyEntityNode(modelElement, node);
};
 
/**
 * @internal
 * Exported only for unit testing
 */
export function preprocessTable(table: ContentModelTable) {
    const sel = getSelectedCells(table);
    table.rows = table.rows
        .map(row => {
            return {
                ...row,
                cells: row.cells.filter(cell => cell.isSelected),
            };
        })
        .filter(row => row.cells.length > 0);
 
    delete table.format.width;
 
    table.widths = sel
        ? table.widths.filter((_, index) => index >= sel?.firstColumn && index <= sel?.lastColumn)
        : [];
}
 
/**
 * @internal
 * Exported only for unit testing
 */
export function shouldPreventDefaultPaste(
    dataTransfer: DataTransfer | null,
    editor: IEditor
): boolean {
    if (!dataTransfer?.items) {
        return false;
    }
 
    if (!editor.getEnvironment().isAndroid) {
        return true;
    }
 
    // On Android, the clipboard data from Office apps is a file, which can't be loaded
    // so we have to allow the default browser behavior
    return toArray(dataTransfer.items).some(item => {
        const { type } = item;
        const isNormalFile = item.kind === 'file' && type !== '';
        const isText = type.indexOf('text/') === 0;
        return isNormalFile || isText;
    });
}
 
/**
 * @internal
 * Create a new instance of CopyPastePlugin
 * @param option The editor option
 */
export function createCopyPastePlugin(
    option: EditorOptions
): PluginWithState<CopyPastePluginState> {
    return new CopyPastePlugin(option);
}