-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
providers.tsx
337 lines (305 loc) · 9.55 KB
/
providers.tsx
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import React, { Reducer, useReducer } from 'react';
import { EuiScreenReaderOnly } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import {
DropIdentifier,
DragDropIdentifier,
RegisteredDropTargets,
DragContextValue,
DragContextState,
CustomMiddleware,
DraggingIdentifier,
} from './types';
import { DEFAULT_DATA_TEST_SUBJ } from '../constants';
import { announce } from './announcements';
const defaultState = {
dragging: undefined,
hoveredDropTarget: undefined,
keyboardMode: false,
dropTargetsByOrder: {},
dataTestSubjPrefix: DEFAULT_DATA_TEST_SUBJ,
};
/**
* The drag / drop context singleton, used like so:
*
* const [ state, dispatch ] = useDragDropContext();
*/
const DragContext = React.createContext<DragContextValue>([defaultState, () => {}]);
export function useDragDropContext() {
const context = React.useContext(DragContext);
if (context === undefined) {
throw new Error(
'useDragDropContext must be used within a <RootDragDropProvider/> or <ChildDragDropProvider/>'
);
}
return context;
}
/**
* The argument to DragDropProvider.
*/
export interface ProviderProps {
/**
* The React children.
*/
children: React.ReactNode;
value: DragContextValue;
}
/**
* A React provider that tracks the dragging state. This should
* be placed at the root of any React application that supports
* drag / drop.
*
* @param props
*/
interface ResetStateAction {
type: 'resetState';
payload?: string;
}
interface EndDraggingAction {
type: 'endDragging';
payload: {
dragging: DraggingIdentifier;
};
}
interface StartDraggingAction {
type: 'startDragging';
payload: {
dragging: DraggingIdentifier;
keyboardMode?: boolean;
};
}
interface LeaveDropTargetAction {
type: 'leaveDropTarget';
}
interface SelectDropTargetAction {
type: 'selectDropTarget';
payload: {
dropTarget: DropIdentifier;
dragging: DragDropIdentifier;
};
}
interface DragToTargetAction {
type: 'dropToTarget';
payload: {
dragging: DragDropIdentifier;
dropTarget: DropIdentifier;
};
}
interface RegisterDropTargetAction {
type: 'registerDropTargets';
payload: RegisteredDropTargets;
}
export type DragDropAction =
| ResetStateAction
| RegisterDropTargetAction
| LeaveDropTargetAction
| SelectDropTargetAction
| DragToTargetAction
| StartDraggingAction
| EndDraggingAction;
const dragDropReducer = (state: DragContextState, action: DragDropAction) => {
switch (action.type) {
case 'resetState':
case 'endDragging':
return {
...state,
dropTargetsByOrder: undefined,
dragging: undefined,
keyboardMode: false,
hoveredDropTarget: undefined,
};
case 'registerDropTargets':
return {
...state,
dropTargetsByOrder: {
...state.dropTargetsByOrder,
...action.payload,
},
};
case 'dropToTarget':
return {
...state,
dropTargetsByOrder: undefined,
dragging: undefined,
keyboardMode: false,
hoveredDropTarget: undefined,
};
case 'leaveDropTarget':
return {
...state,
hoveredDropTarget: undefined,
};
case 'selectDropTarget':
return {
...state,
hoveredDropTarget: action.payload.dropTarget,
};
case 'startDragging':
return {
...state,
...action.payload,
};
default:
return state;
}
};
const useReducerWithMiddleware = (
reducer: Reducer<DragContextState, DragDropAction>,
initState: DragContextState,
middlewareFns?: Array<(action: DragDropAction) => void>
) => {
const [state, dispatch] = useReducer(reducer, initState);
const dispatchWithMiddleware = React.useCallback(
(action: DragDropAction) => {
if (middlewareFns !== undefined && middlewareFns.length > 0) {
middlewareFns.forEach((middlewareFn) => middlewareFn(action));
}
dispatch(action);
},
[middlewareFns]
);
return [state, dispatchWithMiddleware] as const;
};
const useA11yMiddleware = () => {
const [a11yMessage, setA11yMessage] = React.useState('');
const a11yMiddleware = React.useCallback((action: DragDropAction) => {
switch (action.type) {
case 'startDragging':
setA11yMessage(announce.lifted(action.payload.dragging.humanData));
return;
case 'selectDropTarget':
setA11yMessage(
announce.selectedTarget(
action.payload.dragging.humanData,
action.payload.dropTarget.humanData,
action.payload.dropTarget.dropType
)
);
return;
case 'leaveDropTarget':
setA11yMessage(announce.noTarget());
return;
case 'dropToTarget':
const { dragging, dropTarget } = action.payload;
setA11yMessage(
announce.dropped(dragging.humanData, dropTarget.humanData, dropTarget.dropType)
);
return;
case 'endDragging':
setA11yMessage(announce.cancelled(action.payload.dragging.humanData));
return;
default:
return;
}
}, []);
return { a11yMessage, a11yMiddleware };
};
export function RootDragDropProvider({
children,
customMiddleware,
initialState = {},
}: {
children: React.ReactNode;
customMiddleware?: CustomMiddleware;
initialState?: Partial<DragContextState>;
}) {
const { a11yMessage, a11yMiddleware } = useA11yMiddleware();
const middlewareFns = React.useMemo(() => {
return customMiddleware ? [customMiddleware, a11yMiddleware] : [a11yMiddleware];
}, [customMiddleware, a11yMiddleware]);
const dataTestSubj = initialState.dataTestSubjPrefix || DEFAULT_DATA_TEST_SUBJ;
const [state, dispatch] = useReducerWithMiddleware(
dragDropReducer,
{
...defaultState,
...initialState,
},
middlewareFns
);
return (
<>
<ChildDragDropProvider value={[state, dispatch]}>{children}</ChildDragDropProvider>
<EuiScreenReaderOnly>
<div>
<p aria-live="assertive" aria-atomic={true}>
{a11yMessage}
</p>
<p id={`${dataTestSubj}-keyboardInstructionsWithReorder`}>
{i18n.translate('domDragDrop.keyboardInstructionsReorder', {
defaultMessage: `Press space or enter to start dragging. When dragging, use the up/down arrow keys to reorder items in the group and left/right arrow keys to choose drop targets outside of the group. Press space or enter again to finish.`,
})}
</p>
<p id={`${dataTestSubj}-keyboardInstructions`}>
{i18n.translate('domDragDrop.keyboardInstructions', {
defaultMessage: `Press space or enter to start dragging. When dragging, use the left/right arrow keys to move between drop targets. Press space or enter again to finish.`,
})}
</p>
</div>
</EuiScreenReaderOnly>
</>
);
}
export function nextValidDropTarget(
dropTargetsByOrder: RegisteredDropTargets,
hoveredDropTarget: DropIdentifier | undefined,
draggingOrder: [string],
filterElements: (el: DragDropIdentifier) => boolean = () => true,
reverse = false
) {
if (!dropTargetsByOrder) {
return;
}
const filteredTargets = Object.entries(dropTargetsByOrder).filter(([order, dropTarget]) => {
return dropTarget && order !== draggingOrder[0] && filterElements(dropTarget);
});
// filter out secondary targets and targets with the same id as the dragging element
const uniqueIdTargets = filteredTargets.reduce<Array<[string, DropIdentifier]>>(
(acc, current) => {
const [, currentDropTarget] = current;
if (!currentDropTarget) {
return acc;
}
if (acc.find(([, target]) => target?.id === currentDropTarget.id)) {
return acc;
}
return [...acc, current];
},
[]
);
const nextDropTargets = [...uniqueIdTargets, draggingOrder].sort(([orderA], [orderB]) => {
const parsedOrderA = orderA.split(',').map((v) => Number(v));
const parsedOrderB = orderB.split(',').map((v) => Number(v));
const relevantLevel = parsedOrderA.findIndex((v, i) => parsedOrderA[i] !== parsedOrderB[i]);
return parsedOrderA[relevantLevel] - parsedOrderB[relevantLevel];
});
let currentActiveDropIndex = nextDropTargets.findIndex(
([, dropTarget]) => typeof dropTarget === 'object' && dropTarget?.id === hoveredDropTarget?.id
);
if (currentActiveDropIndex === -1) {
currentActiveDropIndex = nextDropTargets.findIndex(
([targetOrder]) => targetOrder === draggingOrder[0]
);
}
const previousElement =
(nextDropTargets.length + currentActiveDropIndex - 1) % nextDropTargets.length;
const nextElement = (currentActiveDropIndex + 1) % nextDropTargets.length;
return nextDropTargets[reverse ? previousElement : nextElement][1];
}
/**
* A React drag / drop provider that derives its state from a RootDragDropProvider. If
* part of a React application is rendered separately from the root, this provider can
* be used to enable drag / drop functionality within the disconnected part.
*
* @param props
*/
export function ChildDragDropProvider({ value, children }: ProviderProps) {
return <DragContext.Provider value={value}>{children}</DragContext.Provider>;
}