Skip to content

Commit

Permalink
add onPaste
Browse files Browse the repository at this point in the history
  • Loading branch information
mxkae committed Jul 2, 2024
1 parent 0bd0a5d commit d5d170c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/block/icon-list-item/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { getUseSvgDef } from '../icon-list/util'
import {
convertToListItems,
useOnSplit,
useOnPaste,
useEnter,
} from './util'

Expand Down Expand Up @@ -95,6 +96,7 @@ const Edit = props => {

const useEnterRef = useEnter( text, clientId )
const onSplit = useOnSplit( clientId, attributes )
const onPaste = useOnPaste( clientId, parentBlock?.clientId, attributes, setAttributes )

const onMerge = forward => {
mergeBlocks( forward )
Expand Down Expand Up @@ -168,6 +170,7 @@ const Edit = props => {
className={ textClassNames }
onSplit={ onSplit }
onMerge={ onMerge }
onPaste={ onPaste }
onReplace={ onReplace
? ( blocks, ...args ) => {
onReplace(
Expand Down
36 changes: 35 additions & 1 deletion src/block/icon-list-item/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
*/
import { useRefEffect } from '@wordpress/compose'
import { useCallback, useRef } from '@wordpress/element'
import { useSelect, useDispatch } from '@wordpress/data'
import {
useSelect, useDispatch, dispatch,
} from '@wordpress/data'
import {
cloneBlock,
switchToBlockType,
Expand Down Expand Up @@ -147,3 +149,35 @@ export const useEnter = ( text, clientId ) => {
[ clientId ]
)
}

export const useOnPaste = ( clientId, parentClientId, attributes, setAttributes ) => {
const { insertBlocks } = useDispatch( blockEditorStore )
const { getBlockIndex } = useSelect( blockEditorStore )

const parser = new DOMParser()

return useCallback( event => {
event.preventDefault()
const content = event.clipboardData.getData( 'text/html' )
const dom = parser.parseFromString( content, 'text/html' )

const listItems = dom.querySelectorAll( 'li' )
const listItemsContent = Array.from( listItems ).map( item => item.innerHTML )

if ( ! attributes.text ) {
const firstItem = listItemsContent.shift()
setAttributes( { text: firstItem } )
}

const newBlocks = listItemsContent.map( text => {
const block = createBlock( 'stackable/icon-list-item', {
...attributes,
text,
} )

return block
} )
dispatch( 'core/block-editor' ).__unstableMarkNextChangeAsNotPersistent()
insertBlocks( newBlocks, getBlockIndex( clientId ) + 1, parentClientId )
}, [ clientId, parentClientId, attributes, setAttributes ] )
}

0 comments on commit d5d170c

Please sign in to comment.