-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
block-wrapper.js
250 lines (224 loc) · 7.1 KB
/
block-wrapper.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
/**
* External dependencies
*/
import classnames from 'classnames';
import { first, last, omit } from 'lodash';
import { animated } from 'react-spring/web.cjs';
/**
* WordPress dependencies
*/
import { useRef, useEffect, useContext, forwardRef } from '@wordpress/element';
import { focus, isTextField, placeCaretAtHorizontalEdge } from '@wordpress/dom';
import { BACKSPACE, DELETE, ENTER } from '@wordpress/keycodes';
import { __, sprintf } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
/**
* Internal dependencies
*/
import { isInsideRootBlock } from '../../utils/dom';
import useMovingAnimation from '../use-moving-animation';
import { Context, SetBlockNodes } from './root-container';
import { BlockListBlockContext } from './block';
import ELEMENTS from './block-wrapper-elements';
const BlockComponent = forwardRef(
( { children, tagName = 'div', __unstableIsHtml, ...props }, wrapper ) => {
const onSelectionStart = useContext( Context );
const setBlockNodes = useContext( SetBlockNodes );
const {
clientId,
rootClientId,
isSelected,
isFirstMultiSelected,
isLastMultiSelected,
isMultiSelecting,
isNavigationMode,
isPartOfMultiSelection,
enableAnimation,
index,
className,
isLocked,
name,
mode,
blockTitle,
wrapperProps,
} = useContext( BlockListBlockContext );
const { initialPosition } = useSelect(
( select ) => {
if ( ! isSelected ) {
return {};
}
return {
initialPosition: select(
'core/block-editor'
).getSelectedBlocksInitialCaretPosition(),
};
},
[ isSelected ]
);
const { removeBlock, insertDefaultBlock } = useDispatch(
'core/block-editor'
);
const fallbackRef = useRef();
const isAligned = wrapperProps && !! wrapperProps[ 'data-align' ];
wrapper = wrapper || fallbackRef;
// Provide the selected node, or the first and last nodes of a multi-
// selection, so it can be used to position the contextual block toolbar.
// We only provide what is necessary, and remove the nodes again when they
// are no longer selected.
useEffect( () => {
if ( isSelected || isFirstMultiSelected || isLastMultiSelected ) {
const node = wrapper.current;
setBlockNodes( ( nodes ) => ( {
...nodes,
[ clientId ]: node,
} ) );
return () => {
setBlockNodes( ( nodes ) => omit( nodes, clientId ) );
};
}
}, [ isSelected, isFirstMultiSelected, isLastMultiSelected ] );
// translators: %s: Type of block (i.e. Text, Image etc)
const blockLabel = sprintf( __( 'Block: %s' ), blockTitle );
// Handing the focus of the block on creation and update
/**
* When a block becomes selected, transition focus to an inner tabbable.
*/
const focusTabbable = () => {
// Focus is captured by the wrapper node, so while focus transition
// should only consider tabbables within editable display, since it
// may be the wrapper itself or a side control which triggered the
// focus event, don't unnecessary transition to an inner tabbable.
if (
document.activeElement &&
isInsideRootBlock( wrapper.current, document.activeElement )
) {
return;
}
// Find all tabbables within node.
const textInputs = focus.tabbable
.find( wrapper.current )
.filter( isTextField )
// Exclude inner blocks and block appenders
.filter(
( node ) =>
isInsideRootBlock( wrapper.current, node ) &&
! node.closest( '.block-list-appender' )
);
// If reversed (e.g. merge via backspace), use the last in the set of
// tabbables.
const isReverse = -1 === initialPosition;
const target =
( isReverse ? last : first )( textInputs ) || wrapper.current;
placeCaretAtHorizontalEdge( target, isReverse );
};
useEffect( () => {
if ( ! isMultiSelecting && ! isNavigationMode && isSelected ) {
focusTabbable();
}
}, [ isSelected, isMultiSelecting, isNavigationMode ] );
// Block Reordering animation
const animationStyle = useMovingAnimation(
wrapper,
isSelected || isPartOfMultiSelection,
isSelected || isFirstMultiSelected,
enableAnimation,
index
);
/**
* Interprets keydown event intent to remove or insert after block if key
* event occurs on wrapper node. This can occur when the block has no text
* fields of its own, particularly after initial insertion, to allow for
* easy deletion and continuous writing flow to add additional content.
*
* @param {KeyboardEvent} event Keydown event.
*/
const onKeyDown = ( event ) => {
const { keyCode, target } = event;
if ( props.onKeyDown ) {
props.onKeyDown( event );
}
if (
keyCode !== ENTER &&
keyCode !== BACKSPACE &&
keyCode !== DELETE
) {
return;
}
if ( target !== wrapper.current || isTextField( target ) ) {
return;
}
event.preventDefault();
if ( keyCode === ENTER ) {
insertDefaultBlock( {}, rootClientId, index + 1 );
} else {
removeBlock( clientId );
}
};
const onMouseLeave = ( { which, buttons } ) => {
// The primary button must be pressed to initiate selection. Fall back
// to `which` if the standard `buttons` property is falsy. There are
// cases where Firefox might always set `buttons` to `0`.
// See https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
// See https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
if ( ( buttons || which ) === 1 ) {
onSelectionStart( clientId );
}
};
const htmlSuffix =
mode === 'html' && ! __unstableIsHtml ? '-visual' : '';
const blockElementId = `block-${ clientId }${ htmlSuffix }`;
const Animated = animated[ tagName ];
const blockWrapper = (
<Animated
// Overrideable props.
aria-label={ blockLabel }
role="group"
{ ...omit( wrapperProps, [ 'data-align' ] ) }
{ ...props }
id={ blockElementId }
ref={ wrapper }
className={ classnames(
className,
props.className,
wrapperProps && wrapperProps.className,
! isAligned && 'wp-block'
) }
data-block={ clientId }
data-type={ name }
data-title={ blockTitle }
// Only allow shortcuts when a blocks is selected and not locked.
onKeyDown={ isSelected && ! isLocked ? onKeyDown : undefined }
// Only allow selection to be started from a selected block.
onMouseLeave={ isSelected ? onMouseLeave : undefined }
tabIndex="0"
style={ {
...( wrapperProps ? wrapperProps.style : {} ),
...( props.style || {} ),
...animationStyle,
} }
>
{ children }
</Animated>
);
// For aligned blocks, provide a wrapper element so the block can be
// positioned relative to the block column.
if ( isAligned ) {
const alignmentWrapperProps = {
'data-align': wrapperProps[ 'data-align' ],
};
return (
<div className="wp-block" { ...alignmentWrapperProps }>
{ blockWrapper }
</div>
);
}
return blockWrapper;
}
);
const ExtendedBlockComponent = ELEMENTS.reduce( ( acc, element ) => {
acc[ element ] = forwardRef( ( props, ref ) => {
return <BlockComponent { ...props } ref={ ref } tagName={ element } />;
} );
return acc;
}, BlockComponent );
export const Block = ExtendedBlockComponent;