-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
block-select-button.js
328 lines (303 loc) · 9.67 KB
/
block-select-button.js
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
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { hasBlockSupport } from '@wordpress/blocks';
import {
Button,
__experimentalHStack as HStack,
__experimentalTruncate as Truncate,
Tooltip,
} from '@wordpress/components';
import { forwardRef } from '@wordpress/element';
import {
Icon,
connection,
lockSmall as lock,
pinSmall,
} from '@wordpress/icons';
import { SPACE, ENTER, BACKSPACE, DELETE } from '@wordpress/keycodes';
import { useSelect, useDispatch } from '@wordpress/data';
import { __unstableUseShortcutEventMatch as useShortcutEventMatch } from '@wordpress/keyboard-shortcuts';
import { __, sprintf } from '@wordpress/i18n';
import isShallowEqual from '@wordpress/is-shallow-equal';
/**
* Internal dependencies
*/
import BlockIcon from '../block-icon';
import useBlockDisplayInformation from '../use-block-display-information';
import useBlockDisplayTitle from '../block-title/use-block-display-title';
import ListViewExpander from './expander';
import { useBlockLock } from '../block-lock';
import { store as blockEditorStore } from '../../store';
import useListViewImages from './use-list-view-images';
import { useListViewContext } from './context';
import { canBindBlock } from '../../hooks/use-bindings-attributes';
function ListViewBlockSelectButton(
{
className,
block: { clientId, name: blockName },
onClick,
onContextMenu,
onMouseDown,
onToggleExpanded,
tabIndex,
onFocus,
onDragStart,
onDragEnd,
draggable,
isExpanded,
ariaLabel,
ariaDescribedBy,
updateFocusAndSelection,
},
ref
) {
const blockInformation = useBlockDisplayInformation( clientId );
const blockTitle = useBlockDisplayTitle( {
clientId,
context: 'list-view',
} );
const { isLocked } = useBlockLock( clientId );
const {
canInsertBlockType,
getSelectedBlockClientIds,
getPreviousBlockClientId,
getBlockRootClientId,
getBlockOrder,
getBlocksByClientId,
getBlockAttributes,
canRemoveBlocks,
} = useSelect( blockEditorStore );
const { duplicateBlocks, multiSelect, removeBlocks } =
useDispatch( blockEditorStore );
const isMatch = useShortcutEventMatch();
const isSticky = blockInformation?.positionType === 'sticky';
const images = useListViewImages( { clientId, isExpanded } );
const { rootClientId } = useListViewContext();
const isConnected = getBlockAttributes( clientId )?.metadata?.bindings;
const positionLabel = blockInformation?.positionLabel
? sprintf(
// translators: 1: Position of selected block, e.g. "Sticky" or "Fixed".
__( 'Position: %1$s' ),
blockInformation.positionLabel
)
: '';
// The `href` attribute triggers the browser's native HTML drag operations.
// When the link is dragged, the element's outerHTML is set in DataTransfer object as text/html.
// We need to clear any HTML drag data to prevent `pasteHandler` from firing
// inside the `useOnBlockDrop` hook.
const onDragStartHandler = ( event ) => {
event.dataTransfer.clearData();
onDragStart?.( event );
};
// Determine which blocks to update:
// If the current (focused) block is part of the block selection, use the whole selection.
// If the focused block is not part of the block selection, only update the focused block.
function getBlocksToUpdate() {
const selectedBlockClientIds = getSelectedBlockClientIds();
const isUpdatingSelectedBlocks =
selectedBlockClientIds.includes( clientId );
const firstBlockClientId = isUpdatingSelectedBlocks
? selectedBlockClientIds[ 0 ]
: clientId;
const firstBlockRootClientId =
getBlockRootClientId( firstBlockClientId );
const blocksToUpdate = isUpdatingSelectedBlocks
? selectedBlockClientIds
: [ clientId ];
return {
blocksToUpdate,
firstBlockClientId,
firstBlockRootClientId,
selectedBlockClientIds,
};
}
/**
* @param {KeyboardEvent} event
*/
async function onKeyDownHandler( event ) {
if ( event.keyCode === ENTER || event.keyCode === SPACE ) {
onClick( event );
} else if (
event.keyCode === BACKSPACE ||
event.keyCode === DELETE ||
isMatch( 'core/block-editor/remove', event )
) {
const {
blocksToUpdate: blocksToDelete,
firstBlockClientId,
firstBlockRootClientId,
selectedBlockClientIds,
} = getBlocksToUpdate();
// Don't update the selection if the blocks cannot be deleted.
if ( ! canRemoveBlocks( blocksToDelete, firstBlockRootClientId ) ) {
return;
}
let blockToFocus =
getPreviousBlockClientId( firstBlockClientId ) ??
// If the previous block is not found (when the first block is deleted),
// fallback to focus the parent block.
firstBlockRootClientId;
removeBlocks( blocksToDelete, false );
// Update the selection if the original selection has been removed.
const shouldUpdateSelection =
selectedBlockClientIds.length > 0 &&
getSelectedBlockClientIds().length === 0;
// If there's no previous block nor parent block, focus the first block.
if ( ! blockToFocus ) {
blockToFocus = getBlockOrder()[ 0 ];
}
updateFocusAndSelection( blockToFocus, shouldUpdateSelection );
} else if ( isMatch( 'core/block-editor/duplicate', event ) ) {
if ( event.defaultPrevented ) {
return;
}
event.preventDefault();
const { blocksToUpdate, firstBlockRootClientId } =
getBlocksToUpdate();
const canDuplicate = getBlocksByClientId( blocksToUpdate ).every(
( block ) => {
return (
!! block &&
hasBlockSupport( block.name, 'multiple', true ) &&
canInsertBlockType( block.name, firstBlockRootClientId )
);
}
);
if ( canDuplicate ) {
const updatedBlocks = await duplicateBlocks(
blocksToUpdate,
false
);
if ( updatedBlocks?.length ) {
// If blocks have been duplicated, focus the first duplicated block.
updateFocusAndSelection( updatedBlocks[ 0 ], false );
}
}
} else if ( isMatch( 'core/block-editor/select-all', event ) ) {
if ( event.defaultPrevented ) {
return;
}
event.preventDefault();
const { firstBlockRootClientId, selectedBlockClientIds } =
getBlocksToUpdate();
const blockClientIds = getBlockOrder( firstBlockRootClientId );
if ( ! blockClientIds.length ) {
return;
}
// If we have selected all sibling nested blocks, try selecting up a level.
// This is a similar implementation to that used by `useSelectAll`.
// `isShallowEqual` is used for the list view instead of a length check,
// as the array of siblings of the currently focused block may be a different
// set of blocks from the current block selection if the user is focused
// on a different part of the list view from the block selection.
if ( isShallowEqual( selectedBlockClientIds, blockClientIds ) ) {
// Only select up a level if the first block is not the root block.
// This ensures that the block selection can't break out of the root block
// used by the list view, if the list view is only showing a partial hierarchy.
if (
firstBlockRootClientId &&
firstBlockRootClientId !== rootClientId
) {
updateFocusAndSelection( firstBlockRootClientId, true );
return;
}
}
// Select all while passing `null` to skip focusing to the editor canvas,
// and retain focus within the list view.
multiSelect(
blockClientIds[ 0 ],
blockClientIds[ blockClientIds.length - 1 ],
null
);
}
}
return (
<>
<Button
className={ classnames(
'block-editor-list-view-block-select-button',
className
) }
onClick={ onClick }
onContextMenu={ onContextMenu }
onKeyDown={ onKeyDownHandler }
onMouseDown={ onMouseDown }
ref={ ref }
tabIndex={ tabIndex }
onFocus={ onFocus }
onDragStart={ onDragStartHandler }
onDragEnd={ onDragEnd }
draggable={ draggable }
href={ `#block-${ clientId }` }
aria-label={ ariaLabel }
aria-describedby={ ariaDescribedBy }
aria-expanded={ isExpanded }
>
<ListViewExpander onClick={ onToggleExpanded } />
<BlockIcon
icon={ blockInformation?.icon }
showColors
context="list-view"
/>
<HStack
alignment="center"
className="block-editor-list-view-block-select-button__label-wrapper"
justify="flex-start"
spacing={ 1 }
>
<span className="block-editor-list-view-block-select-button__title">
<Truncate ellipsizeMode="auto">{ blockTitle }</Truncate>
</span>
{ blockInformation?.anchor && (
<span className="block-editor-list-view-block-select-button__anchor-wrapper">
<Truncate
className="block-editor-list-view-block-select-button__anchor"
ellipsizeMode="auto"
>
{ blockInformation.anchor }
</Truncate>
</span>
) }
{ isConnected && canBindBlock( blockName ) && (
<span className="block-editor-list-view-block-select-button__bindings">
<Icon icon={ connection } />
</span>
) }
{ positionLabel && isSticky && (
<Tooltip text={ positionLabel }>
<Icon icon={ pinSmall } />
</Tooltip>
) }
{ images.length ? (
<span
className="block-editor-list-view-block-select-button__images"
aria-hidden
>
{ images.map( ( image, index ) => (
<span
className="block-editor-list-view-block-select-button__image"
key={ image.clientId }
style={ {
backgroundImage: `url(${ image.url })`,
zIndex: images.length - index, // Ensure the first image is on top, and subsequent images are behind.
} }
/>
) ) }
</span>
) : null }
{ isLocked && (
<span className="block-editor-list-view-block-select-button__lock">
<Icon icon={ lock } />
</span>
) }
</HStack>
</Button>
</>
);
}
export default forwardRef( ListViewBlockSelectButton );