Skip to content

Commit

Permalink
Skip the first onDragOver announcement in Sortable stories
Browse files Browse the repository at this point in the history
The first `onDragOver` event doesn't need to be announced, because it is called immediately after the `onDragStart` announcement
  • Loading branch information
Clauderic Demers committed Aug 25, 2021
1 parent c447880 commit 8844cc7
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions stories/2 - Presets/Sortable/Sortable.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, {useState} from 'react';
import React, {useEffect, useRef, useState} from 'react';
import {createPortal} from 'react-dom';

import {
Expand Down Expand Up @@ -115,6 +115,7 @@ export function Sortable({
coordinateGetter: sortableKeyboardCoordinates,
})
);
const isFirstAnnouncement = useRef(true);
const getIndex = items.indexOf.bind(items);
const getPosition = (id: string) => getIndex(id) + 1;
const activeIndex = activeId ? getIndex(activeId) : -1;
Expand All @@ -128,6 +129,14 @@ export function Sortable({
)} of ${items.length}`;
},
onDragOver(id, overId) {
// In this specific use-case, the picked up item's `id` is always the same as the first `over` id.
// The first `onDragOver` event therefore doesn't need to be announced, because it is called
// immediately after the `onDragStart` announcement and is redundant.
if (isFirstAnnouncement.current === true) {
isFirstAnnouncement.current = false;
return;
}

if (overId) {
return `Sortable item ${id} was moved into position ${getPosition(
overId
Expand All @@ -146,10 +155,18 @@ export function Sortable({
return;
},
onDragCancel(id) {
return `Sorting was cancelled. Sortable item ${id} was dropped.`;
return `Sorting was cancelled. Sortable item ${id} was dropped and returned to position ${getPosition(
id
)} of ${items.length}.`;
},
};

useEffect(() => {
if (!activeId) {
isFirstAnnouncement.current = true;
}
}, [activeId]);

return (
<DndContext
announcements={announcements}
Expand Down

0 comments on commit 8844cc7

Please sign in to comment.