-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
382 lines (333 loc) · 11.5 KB
/
index.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
/**
* External dependencies
*/
import { overEvery, find, findLast, reverse, first, last } from 'lodash';
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
import {
computeCaretRect,
focus,
isHorizontalEdge,
isTextField,
isVerticalEdge,
placeCaretAtHorizontalEdge,
placeCaretAtVerticalEdge,
isEntirelySelected,
} from '@wordpress/dom';
import { UP, DOWN, LEFT, RIGHT, isKeyboardEvent } from '@wordpress/keycodes';
import { withSelect, withDispatch } from '@wordpress/data';
import { compose } from '@wordpress/compose';
/**
* Internal dependencies
*/
import {
isBlockFocusStop,
isInSameBlock,
hasInnerBlocksContext,
} from '../../utils/dom';
/**
* Browser constants
*/
const { getSelection } = window;
/**
* Given an element, returns true if the element is a tabbable text field, or
* false otherwise.
*
* @param {Element} element Element to test.
*
* @return {boolean} Whether element is a tabbable text field.
*/
const isTabbableTextField = overEvery( [
isTextField,
focus.tabbable.isTabbableIndex,
] );
/**
* Returns true if the element should consider edge navigation upon a keyboard
* event of the given directional key code, or false otherwise.
*
* @param {Element} element HTML element to test.
* @param {number} keyCode KeyboardEvent keyCode to test.
* @param {boolean} hasModifier Whether a modifier is pressed.
*
* @return {boolean} Whether element should consider edge navigation.
*/
export function isNavigationCandidate( element, keyCode, hasModifier ) {
const isVertical = ( keyCode === UP || keyCode === DOWN );
// Currently, all elements support unmodified vertical navigation.
if ( isVertical && ! hasModifier ) {
return true;
}
// Native inputs should not navigate horizontally.
const { tagName } = element;
return tagName !== 'INPUT' && tagName !== 'TEXTAREA';
}
class WritingFlow extends Component {
constructor() {
super( ...arguments );
this.onKeyDown = this.onKeyDown.bind( this );
this.bindContainer = this.bindContainer.bind( this );
this.clearVerticalRect = this.clearVerticalRect.bind( this );
this.focusLastTextField = this.focusLastTextField.bind( this );
/**
* Here a rectangle is stored while moving the caret vertically so
* vertical position of the start position can be restored.
* This is to recreate browser behaviour across blocks.
*
* @type {?DOMRect}
*/
this.verticalRect = null;
}
bindContainer( ref ) {
this.container = ref;
}
clearVerticalRect() {
this.verticalRect = null;
}
/**
* Returns the optimal tab target from the given focused element in the
* desired direction. A preference is made toward text fields, falling back
* to the block focus stop if no other candidates exist for the block.
*
* @param {Element} target Currently focused text field.
* @param {boolean} isReverse True if considering as the first field.
*
* @return {?Element} Optimal tab target, if one exists.
*/
getClosestTabbable( target, isReverse ) {
// Since the current focus target is not guaranteed to be a text field,
// find all focusables. Tabbability is considered later.
let focusableNodes = focus.focusable.find( this.container );
if ( isReverse ) {
focusableNodes = reverse( focusableNodes );
}
// Consider as candidates those focusables after the current target.
// It's assumed this can only be reached if the target is focusable
// (on its keydown event), so no need to verify it exists in the set.
focusableNodes = focusableNodes.slice( focusableNodes.indexOf( target ) + 1 );
function isTabCandidate( node, i, array ) {
// Not a candidate if the node is not tabbable.
if ( ! focus.tabbable.isTabbableIndex( node ) ) {
return false;
}
// Prefer text fields...
if ( isTextField( node ) ) {
return true;
}
// ...but settle for block focus stop.
if ( ! isBlockFocusStop( node ) ) {
return false;
}
// If element contains inner blocks, stop immediately at its focus
// wrapper.
if ( hasInnerBlocksContext( node ) ) {
return true;
}
// If navigating out of a block (in reverse), don't consider its
// block focus stop.
if ( node.contains( target ) ) {
return false;
}
// In case of block focus stop, check to see if there's a better
// text field candidate within.
for ( let offset = 1, nextNode; ( nextNode = array[ i + offset ] ); offset++ ) {
// Abort if no longer testing descendents of focus stop.
if ( ! node.contains( nextNode ) ) {
break;
}
// Apply same tests by recursion. This is important to consider
// nestable blocks where we don't want to settle for the inner
// block focus stop.
if ( isTabCandidate( nextNode, i + offset, array ) ) {
return false;
}
}
return true;
}
return find( focusableNodes, isTabCandidate );
}
expandSelection( isReverse ) {
const {
selectedBlockClientId,
selectionStartClientId,
selectionBeforeEndClientId,
selectionAfterEndClientId,
} = this.props;
const nextSelectionEndClientId = isReverse ?
selectionBeforeEndClientId :
selectionAfterEndClientId;
if ( nextSelectionEndClientId ) {
this.props.onMultiSelect(
selectionStartClientId || selectedBlockClientId,
nextSelectionEndClientId
);
}
}
moveSelection( isReverse ) {
const { selectedFirstClientId, selectedLastClientId } = this.props;
const focusedBlockClientId = isReverse ? selectedFirstClientId : selectedLastClientId;
if ( focusedBlockClientId ) {
this.props.onSelectBlock( focusedBlockClientId );
}
}
/**
* Returns true if the given target field is the last in its block which
* can be considered for tab transition. For example, in a block with two
* text fields, this would return true when reversing from the first of the
* two fields, but false when reversing from the second.
*
* @param {Element} target Currently focused text field.
* @param {boolean} isReverse True if considering as the first field.
*
* @return {boolean} Whether field is at edge for tab transition.
*/
isTabbableEdge( target, isReverse ) {
const closestTabbable = this.getClosestTabbable( target, isReverse );
return ! closestTabbable || ! isInSameBlock( target, closestTabbable );
}
onKeyDown( event ) {
const { hasMultiSelection, onMultiSelect, blocks } = this.props;
const { keyCode, target } = event;
const isUp = keyCode === UP;
const isDown = keyCode === DOWN;
const isLeft = keyCode === LEFT;
const isRight = keyCode === RIGHT;
const isReverse = isUp || isLeft;
const isHorizontal = isLeft || isRight;
const isVertical = isUp || isDown;
const isNav = isHorizontal || isVertical;
const isShift = event.shiftKey;
const hasModifier = isShift || event.ctrlKey || event.altKey || event.metaKey;
const isNavEdge = isVertical ? isVerticalEdge : isHorizontalEdge;
// This logic inside this condition needs to be checked before
// the check for event.nativeEvent.defaultPrevented.
// The logic handles meta+a keypress and this event is default prevented by TinyMCE.
if ( ! isNav ) {
// Set immediately before the meta+a combination can be pressed.
if ( isKeyboardEvent.primary( event ) ) {
this.isEntirelySelected = isEntirelySelected( target );
}
if ( isKeyboardEvent.primary( event, 'a' ) ) {
// When the target is contentEditable, selection will already
// have been set by TinyMCE earlier in this call stack. We need
// check the previous result, otherwise all blocks will be
// selected right away.
if ( target.isContentEditable ? this.isEntirelySelected : isEntirelySelected( target ) ) {
onMultiSelect( first( blocks ), last( blocks ) );
event.preventDefault();
}
// After pressing primary + A we can assume isEntirelySelected is true.
// Calling right away isEntirelySelected after primary + A may still return false on some browsers.
this.isEntirelySelected = true;
}
return;
}
// Abort if navigation has already been handled (e.g. TinyMCE inline
// boundaries).
if ( event.nativeEvent.defaultPrevented ) {
return;
}
// Abort if our current target is not a candidate for navigation (e.g.
// preserve native input behaviors).
if ( ! isNavigationCandidate( target, keyCode, hasModifier ) ) {
return;
}
if ( ! isVertical ) {
this.verticalRect = null;
} else if ( ! this.verticalRect ) {
this.verticalRect = computeCaretRect( target );
}
if ( isShift && ( hasMultiSelection || (
this.isTabbableEdge( target, isReverse ) &&
isNavEdge( target, isReverse )
) ) ) {
// Shift key is down, and there is multi selection or we're at the end of the current block.
this.expandSelection( isReverse );
event.preventDefault();
} else if ( hasMultiSelection ) {
// Moving from block multi-selection to single block selection
this.moveSelection( isReverse );
event.preventDefault();
} else if ( isVertical && isVerticalEdge( target, isReverse ) ) {
const closestTabbable = this.getClosestTabbable( target, isReverse );
if ( closestTabbable ) {
placeCaretAtVerticalEdge( closestTabbable, isReverse, this.verticalRect );
event.preventDefault();
}
} else if ( isHorizontal && getSelection().isCollapsed && isHorizontalEdge( target, isReverse ) ) {
const closestTabbable = this.getClosestTabbable( target, isReverse );
placeCaretAtHorizontalEdge( closestTabbable, isReverse );
event.preventDefault();
}
}
/**
* Sets focus to the end of the last tabbable text field, if one exists.
*/
focusLastTextField() {
const focusableNodes = focus.focusable.find( this.container );
const target = findLast( focusableNodes, isTabbableTextField );
if ( target ) {
placeCaretAtHorizontalEdge( target, true );
}
}
render() {
const { children } = this.props;
// Disable reason: Wrapper itself is non-interactive, but must capture
// bubbling events from children to determine focus transition intents.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (
<div className="editor-writing-flow">
<div
ref={ this.bindContainer }
onKeyDown={ this.onKeyDown }
onMouseDown={ this.clearVerticalRect }
>
{ children }
</div>
<div
aria-hidden
tabIndex={ -1 }
onClick={ this.focusLastTextField }
className="wp-block editor-writing-flow__click-redirect"
/>
</div>
);
/* eslint-disable jsx-a11y/no-static-element-interactions */
}
}
export default compose( [
withSelect( ( select ) => {
const {
getSelectedBlockClientId,
getMultiSelectedBlocksStartClientId,
getMultiSelectedBlocksEndClientId,
getPreviousBlockClientId,
getNextBlockClientId,
getFirstMultiSelectedBlockClientId,
getLastMultiSelectedBlockClientId,
hasMultiSelection,
getBlockOrder,
} = select( 'core/editor' );
const selectedBlockClientId = getSelectedBlockClientId();
const selectionStartClientId = getMultiSelectedBlocksStartClientId();
const selectionEndClientId = getMultiSelectedBlocksEndClientId();
return {
selectedBlockClientId,
selectionStartClientId,
selectionBeforeEndClientId: getPreviousBlockClientId( selectionEndClientId || selectedBlockClientId ),
selectionAfterEndClientId: getNextBlockClientId( selectionEndClientId || selectedBlockClientId ),
selectedFirstClientId: getFirstMultiSelectedBlockClientId(),
selectedLastClientId: getLastMultiSelectedBlockClientId(),
hasMultiSelection: hasMultiSelection(),
blocks: getBlockOrder(),
};
} ),
withDispatch( ( dispatch ) => {
const { multiSelect, selectBlock } = dispatch( 'core/editor' );
return {
onMultiSelect: multiSelect,
onSelectBlock: selectBlock,
};
} ),
] )( WritingFlow );