Skip to content

Commit d2fa814

Browse files
committed
[Social Link]: Remove block on DELETE if empty url
1 parent f77958c commit d2fa814

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

packages/block-library/src/social-link/edit.js

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,18 @@ import classNames from 'classnames';
66
/**
77
* WordPress dependencies
88
*/
9+
import { useRefEffect } from '@wordpress/compose';
10+
import { DELETE } from '@wordpress/keycodes';
11+
import { useDispatch } from '@wordpress/data';
12+
913
import {
1014
InspectorControls,
1115
URLPopover,
1216
URLInput,
1317
useBlockProps,
18+
store as blockEditorStore,
1419
} from '@wordpress/block-editor';
15-
import { useState } from '@wordpress/element';
20+
import { useState, useRef } from '@wordpress/element';
1621
import {
1722
Button,
1823
PanelBody,
@@ -27,11 +32,35 @@ import { keyboardReturn } from '@wordpress/icons';
2732
*/
2833
import { getIconBySite, getNameBySite } from './social-list';
2934

35+
function useOnDelete( props ) {
36+
const { removeBlock } = useDispatch( blockEditorStore );
37+
const propsRef = useRef( props );
38+
propsRef.current = props;
39+
return useRefEffect( ( element ) => {
40+
function onKeyDown( event ) {
41+
const { url, clientId } = propsRef.current;
42+
if (
43+
!! url ||
44+
event.defaultPrevented ||
45+
event.keyCode !== DELETE
46+
) {
47+
return;
48+
}
49+
removeBlock( clientId );
50+
}
51+
element.addEventListener( 'keydown', onKeyDown );
52+
return () => {
53+
element.removeEventListener( 'keydown', onKeyDown );
54+
};
55+
}, [] );
56+
}
57+
3058
const SocialLinkURLPopover = ( {
3159
url,
3260
setAttributes,
3361
setPopover,
3462
popoverAnchor,
63+
clientId,
3564
} ) => (
3665
<URLPopover anchor={ popoverAnchor } onClose={ () => setPopover( false ) }>
3766
<form
@@ -40,6 +69,7 @@ const SocialLinkURLPopover = ( {
4069
event.preventDefault();
4170
setPopover( false );
4271
} }
72+
ref={ useOnDelete( { url, clientId } ) }
4373
>
4474
<div className="block-editor-url-input">
4575
<URLInput
@@ -66,6 +96,7 @@ const SocialLinkEdit = ( {
6696
context,
6797
isSelected,
6898
setAttributes,
99+
clientId,
69100
} ) => {
70101
const { url, service, label, rel } = attributes;
71102
const { showLabels, iconColorValue, iconBackgroundColorValue } = context;
@@ -143,6 +174,7 @@ const SocialLinkEdit = ( {
143174
setAttributes={ setAttributes }
144175
setPopover={ setPopover }
145176
popoverAnchor={ popoverAnchor }
177+
clientId={ clientId }
146178
/>
147179
) }
148180
</Button>

0 commit comments

Comments
 (0)