-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
640 lines (574 loc) · 18 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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/**
* External dependencies
*/
import { overEvery, find, findLast, reverse, first, last } from 'lodash';
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { useRef, useEffect } from '@wordpress/element';
import {
computeCaretRect,
focus,
isHorizontalEdge,
isTextField,
isVerticalEdge,
placeCaretAtHorizontalEdge,
placeCaretAtVerticalEdge,
isEntirelySelected,
} from '@wordpress/dom';
import {
UP,
DOWN,
LEFT,
RIGHT,
TAB,
isKeyboardEvent,
ESCAPE,
} from '@wordpress/keycodes';
import { useSelect, useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import {
isBlockFocusStop,
isInSameBlock,
hasInnerBlocksContext,
isInsideRootBlock,
getBlockDOMNode,
getBlockClientId,
} from '../../utils/dom';
import FocusCapture from './focus-capture';
/**
* Browser constants
*/
const { getSelection, getComputedStyle } = 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';
}
/**
* 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.
* @param {Element} containerElement Element containing all blocks.
* @param {boolean} onlyVertical Wether to only consider tabbable elements
* that are visually above or under the
* target.
*
* @return {?Element} Optimal tab target, if one exists.
*/
export function getClosestTabbable(
target,
isReverse,
containerElement,
onlyVertical
) {
// 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( containerElement );
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
);
let targetRect;
if ( onlyVertical ) {
targetRect = target.getBoundingClientRect();
}
function isTabCandidate( node, i, array ) {
// Not a candidate if the node is not tabbable.
if ( ! focus.tabbable.isTabbableIndex( node ) ) {
return false;
}
if ( onlyVertical ) {
const nodeRect = node.getBoundingClientRect();
if (
nodeRect.left >= targetRect.right ||
nodeRect.right <= targetRect.left
) {
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 );
}
function selector( select ) {
const {
getSelectedBlockClientId,
getMultiSelectedBlocksStartClientId,
getMultiSelectedBlocksEndClientId,
getPreviousBlockClientId,
getNextBlockClientId,
getFirstMultiSelectedBlockClientId,
getLastMultiSelectedBlockClientId,
hasMultiSelection,
getBlockOrder,
isNavigationMode,
isSelectionEnabled,
getBlockSelectionStart,
isMultiSelecting,
} = select( 'core/block-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(),
isNavigationMode: isNavigationMode(),
isSelectionEnabled: isSelectionEnabled(),
blockSelectionStart: getBlockSelectionStart(),
isMultiSelecting: isMultiSelecting(),
};
}
/**
* Handles selection and navigation across blocks. This component should be
* wrapped around BlockList.
*/
export default function WritingFlow( { children } ) {
const container = useRef();
const focusCaptureBeforeRef = useRef();
const focusCaptureAfterRef = useRef();
const multiSelectionContainer = useRef();
const entirelySelected = useRef();
// Reference that holds the a flag for enabling or disabling
// capturing on the focus capture elements.
const noCapture = useRef();
// Here a DOMRect 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.
const verticalRect = useRef();
const {
selectedBlockClientId,
selectionStartClientId,
selectionBeforeEndClientId,
selectionAfterEndClientId,
selectedFirstClientId,
selectedLastClientId,
hasMultiSelection,
blocks,
isNavigationMode,
isSelectionEnabled,
blockSelectionStart,
isMultiSelecting,
} = useSelect( selector, [] );
const {
multiSelect,
selectBlock,
clearSelectedBlock,
setNavigationMode,
} = useDispatch( 'core/block-editor' );
function onMouseDown( event ) {
verticalRect.current = null;
// Clicking inside a selected block should exit navigation mode.
if (
isNavigationMode &&
selectedBlockClientId &&
isInsideRootBlock(
getBlockDOMNode( selectedBlockClientId ),
event.target
)
) {
setNavigationMode( false );
}
// Multi-select blocks when Shift+clicking.
if (
isSelectionEnabled &&
// The main button.
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
event.button === 0
) {
const clientId = getBlockClientId( event.target );
if ( clientId ) {
if ( event.shiftKey ) {
if ( blockSelectionStart !== clientId ) {
multiSelect( blockSelectionStart, clientId );
event.preventDefault();
}
// Allow user to escape out of a multi-selection to a singular
// selection of a block via click. This is handled here since
// focus handling excludes blocks when there is multiselection,
// as focus can be incurred by starting a multiselection (focus
// moved to first block's multi-controls).
} else if ( hasMultiSelection ) {
selectBlock( clientId );
}
}
}
}
function expandSelection( isReverse ) {
const nextSelectionEndClientId = isReverse
? selectionBeforeEndClientId
: selectionAfterEndClientId;
if ( nextSelectionEndClientId ) {
multiSelect(
selectionStartClientId || selectedBlockClientId,
nextSelectionEndClientId
);
}
}
function moveSelection( isReverse ) {
const focusedBlockClientId = isReverse
? selectedFirstClientId
: selectedLastClientId;
if ( focusedBlockClientId ) {
selectBlock( 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.
*/
function isTabbableEdge( target, isReverse ) {
const closestTabbable = getClosestTabbable(
target,
isReverse,
container.current
);
return ! closestTabbable || ! isInSameBlock( target, closestTabbable );
}
function onKeyDown( event ) {
const { keyCode, target } = event;
const isUp = keyCode === UP;
const isDown = keyCode === DOWN;
const isLeft = keyCode === LEFT;
const isRight = keyCode === RIGHT;
const isTab = keyCode === TAB;
const isEscape = keyCode === ESCAPE;
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;
// In navigation mode, tab and arrows navigate from block to block.
if ( isNavigationMode ) {
const navigateUp = ( isTab && isShift ) || isUp;
const navigateDown = ( isTab && ! isShift ) || isDown;
const focusedBlockUid = navigateUp
? selectionBeforeEndClientId
: selectionAfterEndClientId;
if ( navigateDown || navigateUp ) {
if ( focusedBlockUid ) {
event.preventDefault();
selectBlock( focusedBlockUid );
} else if ( isTab && selectedBlockClientId ) {
const wrapper = getBlockDOMNode( selectedBlockClientId );
let nextTabbable;
if ( navigateDown ) {
nextTabbable = focus.tabbable.findNext( wrapper );
} else {
nextTabbable = focus.tabbable.findPrevious( wrapper );
}
if ( nextTabbable ) {
event.preventDefault();
nextTabbable.focus();
clearSelectedBlock();
}
}
}
return;
}
// In Edit mode, Tab should focus the first tabbable element after the
// content, which is normally the sidebar (with block controls) and
// Shift+Tab should focus the first tabbable element before the content,
// which is normally the block toolbar.
// Arrow keys can be used, and Tab and arrow keys can be used in
// Navigation mode (press Esc), to navigate through blocks.
if ( selectedBlockClientId ) {
if ( isTab ) {
const wrapper = getBlockDOMNode( selectedBlockClientId );
if ( isShift ) {
if ( target === wrapper ) {
// Disable focus capturing on the focus capture element, so
// it doesn't refocus this block and so it allows default
// behaviour (moving focus to the next tabbable element).
noCapture.current = true;
focusCaptureBeforeRef.current.focus();
return;
}
} else {
const tabbables = focus.tabbable.find( wrapper );
const lastTabbable = last( tabbables ) || wrapper;
if ( target === lastTabbable ) {
// See comment above.
noCapture.current = true;
focusCaptureAfterRef.current.focus();
return;
}
}
} else if ( isEscape ) {
setNavigationMode( true );
}
} else if (
hasMultiSelection &&
isTab &&
target === multiSelectionContainer.current
) {
// See comment above.
noCapture.current = true;
if ( isShift ) {
focusCaptureBeforeRef.current.focus();
} else {
focusCaptureAfterRef.current.focus();
}
return;
}
// When presing any key other than up or down, the initial vertical
// position must ALWAYS be reset. The vertical position is saved so it
// can be restored as well as possible on sebsequent vertical arrow key
// presses. It may not always be possible to restore the exact same
// position (such as at an empty line), so it wouldn't be good to
// compute the position right before any vertical arrow key press.
if ( ! isVertical ) {
verticalRect.current = null;
} else if ( ! verticalRect.current ) {
verticalRect.current = computeCaretRect();
}
// 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 RichText.
if ( ! isNav ) {
// Set immediately before the meta+a combination can be pressed.
if ( isKeyboardEvent.primary( event ) ) {
entirelySelected.current = isEntirelySelected( target );
}
if ( isKeyboardEvent.primary( event, 'a' ) ) {
// When the target is contentEditable, selection will already
// have been set by the browser earlier in this call stack. We
// need check the previous result, otherwise all blocks will be
// selected right away.
if (
target.isContentEditable
? entirelySelected.current
: isEntirelySelected( target )
) {
multiSelect( 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.
entirelySelected.current = true;
}
return;
}
// Abort if navigation has already been handled (e.g. RichText 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;
}
// In the case of RTL scripts, right means previous and left means next,
// which is the exact reverse of LTR.
const { direction } = getComputedStyle( target );
const isReverseDir = direction === 'rtl' ? ! isReverse : isReverse;
if ( isShift ) {
if (
// Ensure that there is a target block.
( ( isReverse && selectionBeforeEndClientId ) ||
( ! isReverse && selectionAfterEndClientId ) ) &&
( hasMultiSelection ||
( 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.
expandSelection( isReverse );
event.preventDefault();
}
} else if ( hasMultiSelection ) {
// Moving from block multi-selection to single block selection
moveSelection( isReverse );
event.preventDefault();
} else if ( isVertical && isVerticalEdge( target, isReverse ) ) {
const closestTabbable = getClosestTabbable(
target,
isReverse,
container.current,
true
);
if ( closestTabbable ) {
placeCaretAtVerticalEdge(
closestTabbable,
isReverse,
verticalRect.current
);
event.preventDefault();
}
} else if (
isHorizontal &&
getSelection().isCollapsed &&
isHorizontalEdge( target, isReverseDir )
) {
const closestTabbable = getClosestTabbable(
target,
isReverseDir,
container.current
);
placeCaretAtHorizontalEdge( closestTabbable, isReverseDir );
event.preventDefault();
}
}
function focusLastTextField() {
const focusableNodes = focus.focusable.find( container.current );
const target = findLast( focusableNodes, isTabbableTextField );
if ( target ) {
placeCaretAtHorizontalEdge( target, true );
}
}
useEffect( () => {
if ( hasMultiSelection && ! isMultiSelecting ) {
multiSelectionContainer.current.focus();
}
}, [ hasMultiSelection, isMultiSelecting ] );
const className = classnames( 'block-editor-writing-flow', {
'is-navigate-mode': isNavigationMode,
} );
// 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={ className }>
<FocusCapture
ref={ focusCaptureBeforeRef }
selectedClientId={ selectedBlockClientId }
containerRef={ container }
noCapture={ noCapture }
hasMultiSelection={ hasMultiSelection }
multiSelectionContainer={ multiSelectionContainer }
/>
<div
ref={ container }
onKeyDown={ onKeyDown }
onMouseDown={ onMouseDown }
>
<div
ref={ multiSelectionContainer }
tabIndex={ hasMultiSelection ? '0' : undefined }
aria-label={
hasMultiSelection
? __( 'Multiple selected blocks' )
: undefined
}
// Needs to be positioned within the viewport, so focus to this
// element does not scroll the page.
style={ { position: 'fixed' } }
/>
{ children }
</div>
<FocusCapture
ref={ focusCaptureAfterRef }
selectedClientId={ selectedBlockClientId }
containerRef={ container }
noCapture={ noCapture }
hasMultiSelection={ hasMultiSelection }
multiSelectionContainer={ multiSelectionContainer }
isReverse
/>
<div
aria-hidden
tabIndex={ -1 }
onClick={ focusLastTextField }
className="block-editor-writing-flow__click-redirect"
/>
</div>
);
/* eslint-enable jsx-a11y/no-static-element-interactions */
}