Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rich text: extract paste handler #31619

Merged
merged 1 commit into from
May 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 11 additions & 85 deletions packages/rich-text/src/component/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
useLayoutEffect,
} from '@wordpress/element';
import { BACKSPACE, DELETE, ENTER, SPACE } from '@wordpress/keycodes';
import { getFilesFromDataTransfer } from '@wordpress/dom';
import { useMergeRefs } from '@wordpress/compose';

/**
Expand All @@ -33,10 +32,10 @@ import { useFormatTypes } from './use-format-types';
import { useDefaultStyle } from './use-default-style';
import { useBoundaryStyle } from './use-boundary-style';
import { useInlineWarning } from './use-inline-warning';
import { insert } from '../insert';
import { useCopyHandler } from './use-copy-handler';
import { useFormatBoundaries } from './use-format-boundaries';
import { useUndoAutomaticChange } from './use-undo-automatic-change';
import { usePasteHandler } from './use-paste-handler';

/** @typedef {import('@wordpress/element').WPSyntheticEvent} WPSyntheticEvent */

Expand Down Expand Up @@ -275,88 +274,6 @@ function RichText(
} );
}

/**
* Handles a paste event.
*
* Saves the pasted data as plain text in `pastedPlainText`.
*
* @param {ClipboardEvent} event The paste event.
*/
function handlePaste( event ) {
if ( ! isSelected ) {
event.preventDefault();
return;
}

const { clipboardData } = event;

let plainText = '';
let html = '';

// IE11 only supports `Text` as an argument for `getData` and will
// otherwise throw an invalid argument error, so we try the standard
// arguments first, then fallback to `Text` if they fail.
try {
plainText = clipboardData.getData( 'text/plain' );
html = clipboardData.getData( 'text/html' );
} catch ( error1 ) {
try {
html = clipboardData.getData( 'Text' );
} catch ( error2 ) {
// Some browsers like UC Browser paste plain text by default and
// don't support clipboardData at all, so allow default
// behaviour.
return;
}
}

event.preventDefault();

// Allows us to ask for this information when we get a report.
window.console.log( 'Received HTML:\n\n', html );
window.console.log( 'Received plain text:\n\n', plainText );

if ( disableFormats ) {
handleChange( insert( record.current, plainText ) );
return;
}

const transformed = formatTypes.reduce(
( accumlator, { __unstablePasteRule } ) => {
// Only allow one transform.
if ( __unstablePasteRule && accumlator === record.current ) {
accumlator = __unstablePasteRule( record.current, {
html,
plainText,
} );
}

return accumlator;
},
record.current
);

if ( transformed !== record.current ) {
handleChange( transformed );
return;
}

if ( onPaste ) {
const files = getFilesFromDataTransfer( clipboardData );
const isInternal = clipboardData.getData( 'rich-text' ) === 'true';

onPaste( {
value: removeEditorOnlyFormats( record.current ),
onChange: handleChange,
html,
plainText,
isInternal,
files: [ ...files ],
activeFormats,
} );
}
}

/**
* Handles delete on keydown:
* - outdent list items,
Expand Down Expand Up @@ -902,9 +819,18 @@ function RichText(
useCopyHandler( { record, multilineTag, preserveWhiteSpace } ),
useFormatBoundaries( { record, applyRecord, setActiveFormats } ),
useUndoAutomaticChange( { didAutomaticChange, undo } ),
usePasteHandler( {
isSelected,
disableFormats,
handleChange,
record,
formatTypes,
onPaste,
removeEditorOnlyFormats,
activeFormats,
} ),
] ),
className: 'rich-text',
onPaste: handlePaste,
onInput: handleInput,
onCompositionStart: handleCompositionStart,
onCompositionEnd: handleCompositionEnd,
Expand Down
112 changes: 112 additions & 0 deletions packages/rich-text/src/component/use-paste-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* WordPress dependencies
*/
import { useRef } from '@wordpress/element';
import { useRefEffect } from '@wordpress/compose';
import { getFilesFromDataTransfer } from '@wordpress/dom';

/**
* Internal dependencies
*/
import { insert } from '../insert';

export function usePasteHandler( props ) {
const propsRef = useRef( props );
propsRef.current = props;
return useRefEffect( ( element ) => {
function _onPaste( event ) {
const {
isSelected,
disableFormats,
handleChange,
record,
formatTypes,
onPaste,
removeEditorOnlyFormats,
activeFormats,
} = propsRef.current;

if ( ! isSelected ) {
event.preventDefault();
return;
}

const { clipboardData } = event;

let plainText = '';
let html = '';

// IE11 only supports `Text` as an argument for `getData` and will
// otherwise throw an invalid argument error, so we try the standard
// arguments first, then fallback to `Text` if they fail.
try {
plainText = clipboardData.getData( 'text/plain' );
html = clipboardData.getData( 'text/html' );
} catch ( error1 ) {
try {
html = clipboardData.getData( 'Text' );
} catch ( error2 ) {
// Some browsers like UC Browser paste plain text by default and
// don't support clipboardData at all, so allow default
// behaviour.
return;
}
}

event.preventDefault();

// Allows us to ask for this information when we get a report.
window.console.log( 'Received HTML:\n\n', html );
window.console.log( 'Received plain text:\n\n', plainText );

if ( disableFormats ) {
handleChange( insert( record.current, plainText ) );
return;
}

const transformed = formatTypes.reduce(
( accumlator, { __unstablePasteRule } ) => {
// Only allow one transform.
if (
__unstablePasteRule &&
accumlator === record.current
) {
accumlator = __unstablePasteRule( record.current, {
html,
plainText,
} );
}

return accumlator;
},
record.current
);

if ( transformed !== record.current ) {
handleChange( transformed );
return;
}

if ( onPaste ) {
const files = getFilesFromDataTransfer( clipboardData );
const isInternal =
clipboardData.getData( 'rich-text' ) === 'true';

onPaste( {
value: removeEditorOnlyFormats( record.current ),
onChange: handleChange,
html,
plainText,
isInternal,
files: [ ...files ],
activeFormats,
} );
}
}

element.addEventListener( 'paste', _onPaste );
return () => {
element.removeEventListener( 'paste', _onPaste );
};
}, [] );
}