-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
258 lines (232 loc) · 7.2 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
/**
* WordPress dependencies
*/
import { useDispatch, useSelect, useRegistry } from '@wordpress/data';
import { useCallback, useState } from '@wordpress/element';
import {
useThrottle,
__experimentalUseDropZone as useDropZone,
} from '@wordpress/compose';
import { isRTL } from '@wordpress/i18n';
import { isUnmodifiedDefaultBlock as getIsUnmodifiedDefaultBlock } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import useOnBlockDrop from '../use-on-block-drop';
import {
getDistanceToNearestEdge,
isPointContainedByRect,
} from '../../utils/math';
import { store as blockEditorStore } from '../../store';
/** @typedef {import('../../utils/math').WPPoint} WPPoint */
/** @typedef {import('../use-on-block-drop/types').WPDropOperation} WPDropOperation */
/**
* The orientation of a block list.
*
* @typedef {'horizontal'|'vertical'|undefined} WPBlockListOrientation
*/
/**
* The insert position when dropping a block.
*
* @typedef {'before'|'after'} WPInsertPosition
*/
/**
* @typedef {Object} WPBlockData
* @property {boolean} isUnmodifiedDefaultBlock Is the block unmodified default block.
* @property {() => DOMRect} getBoundingClientRect Get the bounding client rect of the block.
* @property {number} blockIndex The index of the block.
*/
/**
* Get the drop target position from a given drop point and the orientation.
*
* @param {WPBlockData[]} blocksData The block data list.
* @param {WPPoint} position The position of the item being dragged.
* @param {WPBlockListOrientation} orientation The orientation of the block list.
* @return {[number, WPDropOperation]} The drop target position.
*/
export function getDropTargetPosition(
blocksData,
position,
orientation = 'vertical'
) {
const allowedEdges =
orientation === 'horizontal'
? [ 'left', 'right' ]
: [ 'top', 'bottom' ];
const isRightToLeft = isRTL();
let nearestIndex = 0;
let insertPosition = 'before';
let minDistance = Infinity;
blocksData.forEach(
( { isUnmodifiedDefaultBlock, getBoundingClientRect, blockIndex } ) => {
const rect = getBoundingClientRect();
let [ distance, edge ] = getDistanceToNearestEdge(
position,
rect,
allowedEdges
);
// Prioritize the element if the point is inside of an unmodified default block.
if (
isUnmodifiedDefaultBlock &&
isPointContainedByRect( position, rect )
) {
distance = 0;
}
if ( distance < minDistance ) {
// Where the dropped block will be inserted on the nearest block.
insertPosition =
edge === 'bottom' ||
( ! isRightToLeft && edge === 'right' ) ||
( isRightToLeft && edge === 'left' )
? 'after'
: 'before';
// Update the currently known best candidate.
minDistance = distance;
nearestIndex = blockIndex;
}
}
);
const adjacentIndex =
nearestIndex + ( insertPosition === 'after' ? 1 : -1 );
const isNearestBlockUnmodifiedDefaultBlock =
!! blocksData[ nearestIndex ]?.isUnmodifiedDefaultBlock;
const isAdjacentBlockUnmodifiedDefaultBlock =
!! blocksData[ adjacentIndex ]?.isUnmodifiedDefaultBlock;
// If both blocks are not unmodified default blocks then just insert between them.
if (
! isNearestBlockUnmodifiedDefaultBlock &&
! isAdjacentBlockUnmodifiedDefaultBlock
) {
// If the user is dropping to the trailing edge of the block
// add 1 to the index to represent dragging after.
const insertionIndex =
insertPosition === 'after' ? nearestIndex + 1 : nearestIndex;
return [ insertionIndex, 'insert' ];
}
// Otherwise, replace the nearest unmodified default block.
return [
isNearestBlockUnmodifiedDefaultBlock ? nearestIndex : adjacentIndex,
'replace',
];
}
/**
* @typedef {Object} WPBlockDropZoneConfig
* @property {?HTMLElement} dropZoneElement Optional element to be used as the drop zone.
* @property {string} rootClientId The root client id for the block list.
*/
/**
* A React hook that can be used to make a block list handle drag and drop.
*
* @param {WPBlockDropZoneConfig} dropZoneConfig configuration data for the drop zone.
*/
export default function useBlockDropZone( {
dropZoneElement,
// An undefined value represents a top-level block. Default to an empty
// string for this so that `targetRootClientId` can be easily compared to
// values returned by the `getRootBlockClientId` selector, which also uses
// an empty string to represent top-level blocks.
rootClientId: targetRootClientId = '',
} = {} ) {
const registry = useRegistry();
const [ dropTarget, setDropTarget ] = useState( {
index: null,
operation: 'insert',
} );
const isDisabled = useSelect(
( select ) => {
const {
__unstableIsWithinBlockOverlay,
__unstableHasActiveBlockOverlayActive,
getBlockEditingMode,
} = select( blockEditorStore );
const blockEditingMode = getBlockEditingMode( targetRootClientId );
return (
blockEditingMode !== 'default' ||
__unstableHasActiveBlockOverlayActive( targetRootClientId ) ||
__unstableIsWithinBlockOverlay( targetRootClientId )
);
},
[ targetRootClientId ]
);
const { getBlockListSettings, getBlocks, getBlockIndex } =
useSelect( blockEditorStore );
const { showInsertionPoint, hideInsertionPoint } =
useDispatch( blockEditorStore );
const onBlockDrop = useOnBlockDrop( targetRootClientId, dropTarget.index, {
operation: dropTarget.operation,
} );
const throttled = useThrottle(
useCallback(
( event, ownerDocument ) => {
const blocks = getBlocks( targetRootClientId );
// The block list is empty, don't show the insertion point but still allow dropping.
if ( blocks.length === 0 ) {
registry.batch( () => {
setDropTarget( {
index: 0,
operation: 'insert',
} );
showInsertionPoint( targetRootClientId, 0, {
operation: 'insert',
} );
} );
return;
}
const blocksData = blocks.map( ( block ) => {
const clientId = block.clientId;
return {
isUnmodifiedDefaultBlock:
getIsUnmodifiedDefaultBlock( block ),
getBoundingClientRect: () =>
ownerDocument
.getElementById( `block-${ clientId }` )
.getBoundingClientRect(),
blockIndex: getBlockIndex( clientId ),
};
} );
const [ targetIndex, operation ] = getDropTargetPosition(
blocksData,
{ x: event.clientX, y: event.clientY },
getBlockListSettings( targetRootClientId )?.orientation
);
registry.batch( () => {
setDropTarget( {
index: targetIndex,
operation,
} );
showInsertionPoint( targetRootClientId, targetIndex, {
operation,
} );
} );
},
[
getBlocks,
targetRootClientId,
getBlockListSettings,
registry,
showInsertionPoint,
getBlockIndex,
]
),
200
);
return useDropZone( {
dropZoneElement,
isDisabled,
onDrop: onBlockDrop,
onDragOver( event ) {
// `currentTarget` is only available while the event is being
// handled, so get it now and pass it to the thottled function.
// https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
throttled( event, event.currentTarget.ownerDocument );
},
onDragLeave() {
throttled.cancel();
hideInsertionPoint();
},
onDragEnd() {
throttled.cancel();
hideInsertionPoint();
},
} );
}