-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
block.js
434 lines (397 loc) · 12.3 KB
/
block.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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { hasBlockSupport } from '@wordpress/blocks';
import {
__experimentalTreeGridCell as TreeGridCell,
__experimentalTreeGridItem as TreeGridItem,
} from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { moreVertical } from '@wordpress/icons';
import {
useCallback,
useMemo,
useState,
useRef,
memo,
} from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
import { sprintf, __ } from '@wordpress/i18n';
import { ESCAPE } from '@wordpress/keycodes';
/**
* Internal dependencies
*/
import ListViewLeaf from './leaf';
import useListViewScrollIntoView from './use-list-view-scroll-into-view';
import {
BlockMoverUpButton,
BlockMoverDownButton,
} from '../block-mover/button';
import ListViewBlockContents from './block-contents';
import { useListViewContext } from './context';
import { getBlockPositionDescription, focusListItem } from './utils';
import { store as blockEditorStore } from '../../store';
import useBlockDisplayInformation from '../use-block-display-information';
import { useBlockLock } from '../block-lock';
import AriaReferencedText from './aria-referenced-text';
function ListViewBlock( {
block: { clientId },
displacement,
isAfterDraggedBlocks,
isDragged,
isNesting,
isSelected,
isBranchSelected,
selectBlock,
position,
level,
rowCount,
siblingBlockCount,
showBlockMovers,
path,
isExpanded,
selectedClientIds,
isSyncedBranch,
} ) {
const cellRef = useRef( null );
const rowRef = useRef( null );
const settingsRef = useRef( null );
const [ isHovered, setIsHovered ] = useState( false );
const [ settingsAnchorRect, setSettingsAnchorRect ] = useState();
const { isLocked, canEdit, canMove } = useBlockLock( clientId );
const isFirstSelectedBlock =
isSelected && selectedClientIds[ 0 ] === clientId;
const isLastSelectedBlock =
isSelected &&
selectedClientIds[ selectedClientIds.length - 1 ] === clientId;
const { toggleBlockHighlight } = useDispatch( blockEditorStore );
const blockInformation = useBlockDisplayInformation( clientId );
const blockTitle =
blockInformation?.name || blockInformation?.title || __( 'Untitled' );
const { block, blockName, blockEditingMode } = useSelect(
( select ) => {
const { getBlock, getBlockName, getBlockEditingMode } =
select( blockEditorStore );
return {
block: getBlock( clientId ),
blockName: getBlockName( clientId ),
blockEditingMode: getBlockEditingMode( clientId ),
};
},
[ clientId ]
);
const allowRightClickOverrides = useSelect(
( select ) =>
select( blockEditorStore ).getSettings().allowRightClickOverrides,
[]
);
const showBlockActions =
// When a block hides its toolbar it also hides the block settings menu,
// since that menu is part of the toolbar in the editor canvas.
// List View respects this by also hiding the block settings menu.
hasBlockSupport( blockName, '__experimentalToolbar', true ) &&
// Don't show the settings menu if block is disabled or content only.
blockEditingMode === 'default';
const instanceId = useInstanceId( ListViewBlock );
const descriptionId = `list-view-block-select-button__${ instanceId }`;
const {
expand,
collapse,
BlockSettingsMenu,
listViewInstanceId,
expandedState,
setInsertedBlock,
treeGridElementRef,
} = useListViewContext();
// If multiple blocks are selected, deselect all blocks when the user
// presses the escape key.
const onKeyDown = ( event ) => {
if (
event.keyCode === ESCAPE &&
! event.defaultPrevented &&
selectedClientIds.length > 0
) {
event.stopPropagation();
event.preventDefault();
selectBlock( event, undefined );
}
};
const onMouseEnter = useCallback( () => {
setIsHovered( true );
toggleBlockHighlight( clientId, true );
}, [ clientId, setIsHovered, toggleBlockHighlight ] );
const onMouseLeave = useCallback( () => {
setIsHovered( false );
toggleBlockHighlight( clientId, false );
}, [ clientId, setIsHovered, toggleBlockHighlight ] );
const selectEditorBlock = useCallback(
( event ) => {
selectBlock( event, clientId );
event.preventDefault();
},
[ clientId, selectBlock ]
);
const updateFocusAndSelection = useCallback(
( focusClientId, shouldSelectBlock ) => {
if ( shouldSelectBlock ) {
selectBlock( undefined, focusClientId, null, null );
}
focusListItem( focusClientId, treeGridElementRef?.current );
},
[ selectBlock, treeGridElementRef ]
);
const toggleExpanded = useCallback(
( event ) => {
// Prevent shift+click from opening link in a new window when toggling.
event.preventDefault();
event.stopPropagation();
if ( isExpanded === true ) {
collapse( clientId );
} else if ( isExpanded === false ) {
expand( clientId );
}
},
[ clientId, expand, collapse, isExpanded ]
);
// Allow right-clicking an item in the List View to open up the block settings dropdown.
const onContextMenu = useCallback(
( event ) => {
if ( showBlockActions && allowRightClickOverrides ) {
settingsRef.current?.click();
// Ensure the position of the settings dropdown is at the cursor.
setSettingsAnchorRect(
new window.DOMRect( event.clientX, event.clientY, 0, 0 )
);
event.preventDefault();
}
},
[ allowRightClickOverrides, settingsRef, showBlockActions ]
);
const onMouseDown = useCallback(
( event ) => {
// Prevent right-click from focusing the block,
// because focus will be handled when opening the block settings dropdown.
if ( allowRightClickOverrides && event.button === 2 ) {
event.preventDefault();
}
},
[ allowRightClickOverrides ]
);
const settingsPopoverAnchor = useMemo( () => {
const { ownerDocument } = rowRef?.current || {};
// If no custom position is set, the settings dropdown will be anchored to the
// DropdownMenu toggle button.
if ( ! settingsAnchorRect || ! ownerDocument ) {
return undefined;
}
// Position the settings dropdown at the cursor when right-clicking a block.
return {
ownerDocument,
getBoundingClientRect() {
return settingsAnchorRect;
},
};
}, [ settingsAnchorRect ] );
const clearSettingsAnchorRect = useCallback( () => {
// Clear the custom position for the settings dropdown so that it is restored back
// to being anchored to the DropdownMenu toggle button.
setSettingsAnchorRect( undefined );
}, [ setSettingsAnchorRect ] );
// Pass in a ref to the row, so that it can be scrolled
// into view when selected. For long lists, the placeholder for the
// selected block is also observed, within ListViewLeafPlaceholder.
useListViewScrollIntoView( {
isSelected,
rowItemRef: rowRef,
selectedClientIds,
} );
// When switching between rendering modes (such as template preview and content only),
// it is possible for a block to temporarily be unavailable. In this case, we should not
// render the leaf, to avoid errors further down the tree.
if ( ! block ) {
return null;
}
const blockPositionDescription = getBlockPositionDescription(
position,
siblingBlockCount,
level
);
const blockAriaLabel = isLocked
? sprintf(
// translators: %s: The title of the block. This string indicates a link to select the locked block.
__( '%s (locked)' ),
blockTitle
)
: blockTitle;
const settingsAriaLabel = sprintf(
// translators: %s: The title of the block.
__( 'Options for %s' ),
blockTitle
);
const hasSiblings = siblingBlockCount > 0;
const hasRenderedMovers = showBlockMovers && hasSiblings;
const moverCellClassName = classnames(
'block-editor-list-view-block__mover-cell',
{ 'is-visible': isHovered || isSelected }
);
const listViewBlockSettingsClassName = classnames(
'block-editor-list-view-block__menu-cell',
{ 'is-visible': isHovered || isFirstSelectedBlock }
);
let colSpan;
if ( hasRenderedMovers ) {
colSpan = 2;
} else if ( ! showBlockActions ) {
colSpan = 3;
}
const classes = classnames( {
'is-selected': isSelected,
'is-first-selected': isFirstSelectedBlock,
'is-last-selected': isLastSelectedBlock,
'is-branch-selected': isBranchSelected,
'is-synced-branch': isSyncedBranch,
'is-dragging': isDragged,
'has-single-cell': ! showBlockActions,
'is-synced': blockInformation?.isSynced,
'is-draggable': canMove,
'is-displacement-normal': displacement === 'normal',
'is-displacement-up': displacement === 'up',
'is-displacement-down': displacement === 'down',
'is-after-dragged-blocks': isAfterDraggedBlocks,
'is-nesting': isNesting,
} );
// Only include all selected blocks if the currently clicked on block
// is one of the selected blocks. This ensures that if a user attempts
// to alter a block that isn't part of the selection, they're still able
// to do so.
const dropdownClientIds = selectedClientIds.includes( clientId )
? selectedClientIds
: [ clientId ];
// Detect if there is a block in the canvas currently being edited and multi-selection is not happening.
const currentlyEditingBlockInCanvas =
isSelected && selectedClientIds.length === 1;
return (
<ListViewLeaf
className={ classes }
isDragged={ isDragged }
onKeyDown={ onKeyDown }
onMouseEnter={ onMouseEnter }
onMouseLeave={ onMouseLeave }
onFocus={ onMouseEnter }
onBlur={ onMouseLeave }
level={ level }
position={ position }
rowCount={ rowCount }
path={ path }
id={ `list-view-${ listViewInstanceId }-block-${ clientId }` }
data-block={ clientId }
data-expanded={ canEdit ? isExpanded : undefined }
ref={ rowRef }
>
<TreeGridCell
className="block-editor-list-view-block__contents-cell"
colSpan={ colSpan }
ref={ cellRef }
aria-selected={ !! isSelected }
>
{ ( { ref, tabIndex, onFocus } ) => (
<div className="block-editor-list-view-block__contents-container">
<ListViewBlockContents
block={ block }
onClick={ selectEditorBlock }
onContextMenu={ onContextMenu }
onMouseDown={ onMouseDown }
onToggleExpanded={ toggleExpanded }
isSelected={ isSelected }
position={ position }
siblingBlockCount={ siblingBlockCount }
level={ level }
ref={ ref }
tabIndex={
currentlyEditingBlockInCanvas ? 0 : tabIndex
}
onFocus={ onFocus }
isExpanded={ canEdit ? isExpanded : undefined }
selectedClientIds={ selectedClientIds }
ariaLabel={ blockAriaLabel }
ariaDescribedBy={ descriptionId }
updateFocusAndSelection={ updateFocusAndSelection }
/>
<AriaReferencedText id={ descriptionId }>
{ blockPositionDescription }
</AriaReferencedText>
</div>
) }
</TreeGridCell>
{ hasRenderedMovers && (
<>
<TreeGridCell
className={ moverCellClassName }
withoutGridItem
>
<TreeGridItem>
{ ( { ref, tabIndex, onFocus } ) => (
<BlockMoverUpButton
orientation="vertical"
clientIds={ [ clientId ] }
ref={ ref }
tabIndex={ tabIndex }
onFocus={ onFocus }
/>
) }
</TreeGridItem>
<TreeGridItem>
{ ( { ref, tabIndex, onFocus } ) => (
<BlockMoverDownButton
orientation="vertical"
clientIds={ [ clientId ] }
ref={ ref }
tabIndex={ tabIndex }
onFocus={ onFocus }
/>
) }
</TreeGridItem>
</TreeGridCell>
</>
) }
{ showBlockActions && BlockSettingsMenu && (
<TreeGridCell
className={ listViewBlockSettingsClassName }
aria-selected={ !! isSelected }
ref={ settingsRef }
>
{ ( { ref, tabIndex, onFocus } ) => (
<BlockSettingsMenu
clientIds={ dropdownClientIds }
block={ block }
icon={ moreVertical }
label={ settingsAriaLabel }
popoverProps={ {
anchor: settingsPopoverAnchor, // Used to position the settings at the cursor on right-click.
} }
toggleProps={ {
ref,
className: 'block-editor-list-view-block__menu',
tabIndex,
onClick: clearSettingsAnchorRect,
onFocus,
} }
disableOpenOnArrowDown
expand={ expand }
expandedState={ expandedState }
setInsertedBlock={ setInsertedBlock }
__experimentalSelectBlock={
updateFocusAndSelection
}
/>
) }
</TreeGridCell>
) }
</ListViewLeaf>
);
}
export default memo( ListViewBlock );