Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Lens] Refactor drag and drop (#161257)
## Summary When I created drag and drop for Lens, the API I went for was not the most readable one. It was designed this way because I wanted to gain some performance, but it was very hard to maintain the performance gain with a lot of changes in the drag and drop area because all the pieces of the code needed to memoized in a tricky way and it wasn't communicated well. In the end it works even without these tricks so I decided to simplify it in this PR. The main changes include: 1. Instead of multiple `useState` per parameter, we keep all the state in reducer both for `ReorderProvider` and `RootDragDropProvider`. Thanks to that we get multiple improvements: 2. The code in `DragDrop` component becomes more descriptive as we don't run multiple state updates when user executes an action but one state update describing what actually happens (eg. `dispatchDnd({type: 'selectDropTarget' ....})`. The internal logic of the update lives in the reducer. 3. We don't have to pass `trackUiCounterEvents` as another prop to `DragDrop` and run it wherever we need - instead we pass it as a middleware to the context and run before dispatching (and it's very easy to add more middlewares if we need extra integrations at some point!) 4. We also run a11y announcements as a middleware instead of inside `DragDrop` component 5. The `ChildDragDropProvider` props look much cleaner: before: ``` <ChildDragDropProvider keyboardMode={keyboardModeState} setKeyboardMode={setKeyboardModeState} dragging={draggingState.dragging} setA11yMessage={setA11yMessage} setDragging={setDragging} activeDropTarget={activeDropTargetState} setActiveDropTarget={setActiveDropTarget} registerDropTarget={registerDropTarget} dropTargetsByOrder={dropTargetsByOrderState} dataTestSubjPrefix={dataTestSubj} onTrackUICounterEvent={onTrackUICounterEvent} > {children} </ChildDragDropProvider> ``` after: ``` <ChildDragDropProvider value={[state, dispatch]}>{children}</ChildDragDropProvider> ``` 6. Created custom hook `useDragDropContext` instead of using `useContext(DragContext)` and making DragContext private. This way we will avoid potential problems with using context outside of root. 7. Bonus thing - if we ever decide to move to redux, the structure is there already What I am still not happy with is that the tests are very domain-dependant instead of user-driven - instead of checking the store actions, I should check the interface from the user perspective. I will try to work on it once I find some time between more important tasks though.
- Loading branch information