Giter Site home page Giter Site logo

clauderic / dnd-kit Goto Github PK

View Code? Open in Web Editor NEW
11.4K 34.0 581.0 6.74 MB

The modern, lightweight, performant, accessible and extensible drag & drop toolkit for React.

Home Page: http://dndkit.com

License: MIT License

JavaScript 0.50% TypeScript 92.53% HTML 0.20% CSS 6.77%
react draggable droppable sortable drag-and-drop drag

dnd-kit's Introduction

@dnd-kit โ€“ the modern drag & drop toolkit for React

Stable Release Build status gzip size Follow us on Twitter

  • Feature packed: customizable collision detection algorithms, multiple activators, draggable overlay, drag handles, auto-scrolling, constraints, and so much more.
  • Built for React: exposes hooks such as useDraggable and useDroppable. and won't force you to re-architect your app or create additional wrapper DOM nodes.
  • Supports a wide range of use cases: lists, grids, multiple containers, nested contexts, variable sized items, virtualized lists, 2D Games, and more.
  • Zero dependencies and modular: the core of the library weighs around 10kb minified and has no external dependencies. It's built around built-in React state management and context, which keeps the library lean.
  • Built-in support for multiple input methods: Pointer, mouse, touch and keyboard sensors.
  • Fully customizable & extensible: Customize every detail: animations, transitions, behaviours, styles. Build your own sensors, collision detection algorithms, customize key bindings and so much more.
  • Accessibility: Keyboard support, sensible default aria attributes, customizable screen reader instructions and live regions built-in.
  • Performance: It was built with performance in mind in order to support silky smooth animations.
  • Presets: Need to build a sortable interface? Check out @dnd-kit/sortable, which is a thin layer built on top of @dnd-kit/core. More presets coming in the future.

Documentation

To learn how to get started with dnd kit, visit the official documentation website. You'll find in-depth API documentation, tips and guides to help you build drag and drop interfaces.

Visit @dnd-kit documentation

Key concepts

The core library of dnd kit exposes two main concepts:

Augment your existing components using the useDraggable and useDroppable hooks, or combine both to create components that can both be dragged and dropped over.

Handle events and customize the behaviour of your draggable elements and droppable areas using the <DndContext> provider. Configure sensors to handle different input methods.

Use the <DragOverlay> component to render a draggable overlay that is removed from the normal document flow and is positioned relative to the viewport.

Check out our quick start guide to learn how get started.

Extensibility

Extensibility is at the core of dnd kit. It is built to be lean and extensible. It ships with the features we believe most people will want most of the time, and provides extension points to build the rest on top of @dnd-kit/core.

A prime example of the level of extensibility of dnd kit is the Sortable preset, which is built using the extension points that are exposed by @dnd-kit/core.

The primary extension points of dnd kit are:

  • Sensors
  • Modifiers
  • Constraints
  • Custom collision detection algorithms

Accessibility

Building accessible drag and drop interfaces is hard; dnd kit has a number of sensible defaults and starting points to help you make your drag and drop interface accessible:

  • Customizable screen reader instructions for how to interact with draggable items
  • Customizable live region updates to provide screen reader announcements in real-time of what is currently happening with draggable and droppable elements.
  • Sensible defaults for aria attributes that should be passed to draggable items

Check out our Accessibility guide to learn more about how you can help provide a better experience for screen readers.

Architecture

Unlike most drag and drop libraries, dnd kit intentionally is not built on top of the HTML5 Drag and drop API. This was a deliberate architectural decision, that does come with tradeoffs that you should be aware of before deciding to use it, but for most applications, we believe the benefits outweigh the tradeoffs.

The HTML5 Drag and drop API has some severe limitations. It does not support touch devices or using the keyboard to drag items, which means that the libraries that are built on top of it need to expose an entirely different implementation to support those input methods. It also doesn't support common use-cases such as locking dragging to a specific axis or to the bounds of a container, custom collision detection strategies, or even customizing the preview of the dragged item.

While there are workarounds to some of these issues, those workarounds typically increase the complexity of the codebase and the overall bundle size of the library, and lead to inconsistencies between the mouse, touch and keyboard layers because they're powered by entirely different implementations.

The main tradeoff with not using the HTML5 Drag and drop API is that you won't be able to drag from the desktop or between windows. If the drag and drop use-case you have in mind involves this kind of functionality, you'll definitely want to use a library that's built on top of the HTML 5 Drag and drop API. We highly recommend you check out react-dnd for a React library that's has a native HTML 5 Drag and drop backend.

Performance

Minimizing DOM mutations

dnd kit lets you build drag and drop interfaces without having to mutate the DOM every time an item needs to shift position.

This is possible because dnd kit lazily calculates and stores the initial positions and layout of your droppable containers when a drag operation is initiated. These positions are passed down to your components that use useDraggable and useDroppable so that you can compute the new positions of your items while a drag operation is underway, and move them to their new positions using performant CSS properties that do not trigger a repaint such as translate3d and scale. For an example of how this can be achieved, check out the implementation of the sorting strategies that are exposed by the @dnd-kit/sortable library.

This isn't to say that you can't shift the position of the items in the DOM while dragging, this is something that is supported and sometimes inevitable. In some cases, it won't be possible to know in advance what the new position and layout of the item until you move it in the DOM. Just know that these kind of mutations to the DOM while dragging are much more expensive and will cause a repaint, so if possible, prefer computing the new positions using translate3d and scale.

Synthetic events

dnd kit also uses SyntheticEvent listeners for the activator events of all sensors, which leads to improved performance over manually adding event listeners to each individual draggable node.

Playful illustration of draggable and droppable concepts. A robot picks up a draggable card and moves it over a droppable container.

Working in the @dnd-kit repository

Packages contained within this repository

  • @dnd-kit/core
  • @dnd-kit/accessibility
  • @dnd-kit/sortable
  • @dnd-kit/modifiers
  • @dnd-kit/utilities

Installing dependencies

You'll need to install all the dependencies in the root directory. Since the @dnd-kit is a monorepo that uses Lerna and Yarn Workspaces, npm CLI is not supported (only yarn).

yarn install

This will install all dependencies in each project, build them, and symlink them via Lerna

Development workflow

In one terminal, run yarn start in parallel:

yarn start

This builds each package to <packages>/<package>/dist and runs the project in watch mode so any edits you save inside <packages>/<package>/src cause a rebuild to <packages>/<package>/dist. The results will stream to to the terminal.

Running storybook

yarn start:storybook

Runs the storybook Open http://localhost:6006 to view it in the browser.

Screenshot of Storybook running locally

Working with the playground

You can play with local packages in the Parcel-powered playground.

yarn start:playground

This will start the playground on localhost:1234. If you have lerna running watch in parallel mode in one terminal, and then you run parcel, your playground will hot reload when you make changes to any imported module whose source is inside of packages/*/src/*. Note that to accomplish this, each package's start command passes TDSX the --noClean flag. This prevents Parcel from exploding between rebuilds because of File Not Found errors.

Important Safety Tip: When adding/altering packages in the playground, use alias object in package.json. This will tell Parcel to resolve them to the filesystem instead of trying to install the package from NPM. It also fixes duplicate React errors you may run into.

Running Cypress

(In a third terminal) you can run Cypress and it will run the integration tests against storybook.

dnd-kit's People

Contributors

akhmadullin avatar ayc0 avatar ayy-bc avatar cantrellnm avatar clauderic avatar daniguardiola avatar dependabot[bot] avatar finestv avatar github-actions[bot] avatar juan-kang avatar jwr1 avatar kevincrossgrove avatar lsit avatar lukesmurray avatar medihack avatar mitchheddles avatar nauss avatar nickpresta avatar petdud avatar phungleson avatar pustelto avatar py-wai avatar ranbena avatar shajansheriff avatar shayc avatar supersebh avatar tmcw avatar vosatom avatar wmain avatar xstevenyung avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dnd-kit's Issues

[FEATURE] Enable Github Discussions

Hi,

Thanks for the lib. I have some understanding questions about the sensor's and don't want to pollute the issues list.

Would you mind enabling the discussions feature? it's out in beta now.

Thanks!

Incorrect detection of over container with a long scrolling container

I am dragging from one Droppable container to another Droppable/Sortable container. If the source Droppable has many items in it and the the destination Droppable does not have as many items, the over container still registers the source container even though I am over of the destination. Curiously, the source container will scroll until it reaches some threshold and then it correctly detects the correct over container.

Screen.Recording.2021-01-16.at.09.53.24.PM.mp4

DragOverlay Not Working With Sortable Context

Use Case
Users need to be able to move squares around specific squares (in a certain order), so I thought that using SortableContext would be both be the simplest solution that would solve my problem. I'd also love to render a 'default state' of sorts when the users are moving the objects (ie a card with a number shows up)

Problem
When using drag overlay, instead of staying where the original SortableItem was, it moves around alongside the item being moved. Do you know how I could fix this?

Here's a video of the problem

Unique.Expressions.-.Google.Chrome.2021-02-09.08-19-31.mp4

Package Information

{
    "@dnd-kit/core": "^1.0.0",
    "@dnd-kit/sortable": "^1.0.0",
}

Component In Question:

export const ScavengerHunt: React.FC<IScavengerHunt> = ({ questions }) => {
  const [activeId, setActiveId] = useState<null | string>(null);
  const [currentQuestions, setQuestions] = useState(
    questions as Array<ISHModule>
  );
  const sensors = useSensors(
    useSensor(TouchSensor),
    useSensor(MouseSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    const oldId = over ? over.id : "";
    setActiveId(null);
    if (active.id !== oldId) {
      setQuestions((oldQuestions) => {
        const oldIndex = oldQuestions.findIndex(
          (question) => question.id === active.id
        );
        const newIndex = oldQuestions.findIndex(
          (question) => question.id === oldId
        );

        return arrayMove(oldQuestions, oldIndex, newIndex);
      });
    }
  };

  const handleDragStart = (event: DragStartEvent) => {
    const { active } = event;
    setActiveId(active.id);
  };

  const normalizedQuestions = currentQuestions.map((question) => question.id);

  const rows = lodash.chunk(currentQuestions, 3);

  return (
    <DndContext
      sensors={sensors}
      onDragEnd={handleDragEnd}
      onDragStart={handleDragStart}
    >
      <SortableContext items={normalizedQuestions}>
        <Grid container spacing={4}>
          {rows.map((row, index) => {
            const direction = (index + 1) % 2 === 0 ? "row-reverse" : "row";

            return (
              <Grid
                container
                item
                direction={direction}
                key={index}
                spacing={4}
              >
                {row.map((question) => {
                  return (
                    <Grid item xs={4} key={question.id}>
                      <SortableItem id={question.id}>
                        <SHQuestion {...question} />
                      </SortableItem>
                    </Grid>
                  );
                })}
              </Grid>
            );
          })}
        </Grid>
      </SortableContext>
      {createPortal(
        <DragOverlay>{activeId && <p>{activeId}</p>}</DragOverlay>,
        document.body
      )}
    </DndContext>
  );
};

Unwanted animation in sortable list when moving between multiple containers

Hello and thank you for the great library,

I noticed unwanted artefacts in my implementation of a dnd between multiple containers of sortable items, which was an adaptation of your <MultipleContainers /> component demoed in the story.

After a while debugging it, I realised the same visual glitch is present in the story itself.
In order to reproduce it, you can:

That's for the bug itself. Regarding the functionality's API (dragging items from a list to another): do you think users should implement the low level transferring from one list to another themselves, as visible in the current story, or do you think the library should include an easier solution?

Memoize attributes returned from useDraggable unless they change

Hi @clauderic, thanks for great DnD Library.

I'm trying to create sortable nested tree with it. I'm almost done, but since we have quite a lot of items in the tree and so far I couldn't found virtualization library that would support nested structures. So I'm trying to get as much perf as possible through other means (mainly useMemo hooks and React.memo). However I have noticed that attributes object returned from useDraggable is always a new object, even when the data don't change. It would be greate to memoize this in order to make use of memoization on the items.

Sorry if the description is a little short. I may have a look into this and create PR if necessary.

Nested sortable

Hi, I'd like to achieve a nested sortable (where I can drag and drop between different levels) like in this sortablejs example: https://sortablejs.github.io/Sortable/#nested

I've tried to make it based on documentation, but it looks like I cannot even drag outside SortableContext. Am I doing something wrong or is it not possible yet? If so is it planned?

My try: https://codesandbox.io/s/react-nested-dnd-kit-0cimu?file=/src/App.js
(I haven't bothered setting up proper swap logic yet, so any change in order goes back to initialValues after drop)

Consider adding nested drag example

Commonly drag and drop libraries use the example of Trello boards, where you can drag and drop to reorder the items on a board in a list of boards, and then drag and drop to reorder the list of boards.

The cherry on top for an example like this would be using a virtualizer for nested draggable lists, which would showcase how powerful/flexible this library is. (Maybe 100 boards with 1000 items each or something).

edit: (documentation tag should be added)

Spontaneous horizontal scrolling when using useSortable

This issue is visible in the "Many items" multiple container example. Just pick up a single card starts the whole board scrolling rapidly to the right. I guess it's because the card is near the right edge, but in my experimentation it's very hard to get control of that horizontal scrolling if the board is wider than the screen.

Chrome/macOS

ezgif-7-1f35550d9661

Is it possible to tune the scrolling behavior as a client of dnd-kit?

Nesting of Nodes DOES NOT WORK

Hi,

I was in love with this library until i hit this issue. :( I hope you could help me get this resolved.

I have a node that is both draggable and droppable.

I render two nodes into the playground like so

{nodes.map(node => {
return ;
})}

The issues with this approach.

  1. Nodes do not drag smoothly - They flicker when we drag
  2. The node 1 goes under node 2 when dragged over. Both have same z-index. Node 2 goes over node 1 correctly
  3. The over property is null when node 2 is dropped over node 1. This is critical information to establish parent child relationship for nesting.
  4. isOver from both Draggable and Droppable is not working as expected. They are false even when the node is dragged over.

Codesandbox - https://codesandbox.io/s/laughing-roentgen-6jopj

PS: In console log you can see the messages.

Sortable Grid No Longer Updates After A Few Swaps

Issue
Although both kinds of sensors work initially. After a certain number of moves, they stop working altogether. I've checked the event handler, and it never triggered. So I don't think it's an issue with the way I'm handling updates.

Any idea of what it could be? I've attached a video in order to demonstrate the issue.

I followed this portion of the documentation in order to get started: https://docs.dndkit.com/presets/sortable
Code

import { styled, Grid } from "@material-ui/core";
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
  TouchSensor,
} from "@dnd-kit/core";
import React, { useState } from "react";
import { SUQuestion } from "./QuestionCard";
import { questions } from "./square.data";
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
} from "@dnd-kit/sortable";

import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";

export const SquareUP = () => {
  const [currentQuestions, setQuestions] = useState(questions);
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    }),
    useSensor(TouchSensor)
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    const oldId = over ? over.id : "";
    if (active.id !== oldId) {
      setQuestions((oldQuestions) => {
        const oldIndex = oldQuestions.findIndex(
          (question) => question.letter === active.id
        );
        const newIndex = oldQuestions.findIndex(
          (question) => question.letter === oldId
        );
        return arrayMove(oldQuestions, oldIndex, newIndex);
      });
    }
  };

  const normalizedQuestions = currentQuestions.map(
    (question) => question.letter
  );
  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragEnd={handleDragEnd}
    >
      <SortableContext items={normalizedQuestions}>
        <AssignmentContainer>
          <QuestionContainer>
            {currentQuestions.map((question, index) => {
              return (
                <Grid item xs={3} key={index}>
                  <SortableItem id={question.letter}>
                    <SUQuestion {...question} />
                  </SortableItem>
                </Grid>
              );
            })}
          </QuestionContainer>
        </AssignmentContainer>
      </SortableContext>
    </DndContext>
  );
};

const AssignmentContainer = styled("div")(({ theme }) => ({
  display: "flex",
  justifyContent: "center",
  border: "1px solid black",
  maxWidth: theme.spacing(100),
  borderRadius: theme.spacing(1),
}));

const QuestionContainer = styled((props) => <Grid container {...props} />)(
  ({ theme }) => ({
    margin: theme.spacing(2),
    width: "100%",
    justifyContent: "center",
  })
);


const SortableItem: React.FunctionComponent<{ id: string }> = ({
  children,
  id,
}) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
  } = useSortable({ id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    cursor: "pointer",
  };

  return (
    <div ref={setNodeRef} style={style} {...attributes} {...listeners}>
      {children}
    </div>
  );
};

Build playground for every PR

Ideally we should build a hosted version of the playground for every PR. Arguably, the Playground perhaps just needs to belong in Storybook to simplify things.

Test dnd-kit with Jest and React Testing Library

Hello there !

I'm trying to drag and drop element with Jest and React Testing Library. I'm using @dnd-kit/sortable.
I configure my sensors to listen to pointer events and keyboard events. When I testing on a browser both sensore works perfectly but within a Jest / React Testing Library these sensors does'nt work anymore.

For the keyboard way:

  • I press "Enter" on drag handle
  • I press "ArrowDown" (vertical list)
  • I press "Enter" to finish drag and drop process

For the pointer way. I use the dragStart, dragOver and drop function from React Testing Library.

My question Is : Is there a way to test drag and drop in Jest + React Testing Library environment ? Or should I use Cypress ?

Droppable area detect if sortable item dropped over

The docs state: "Use the useDroppable hook to set up DOM nodes as droppable areas that draggable elements can be dropped over."

I'm wandering if it's possible for droppable areas to detect if sortable elements are dropped over them?

Apologies in advance if I've missed something. It was straightforward to create a working example of a droppable area working with a draggable element. I've tried to have a droppable area inside and outside the SortableContext.

Sortable grid with different item sizes

Hey

First thanks for the library, really appreciated!

Based on #41 I tried to create a sortable grid where the items have a different row/col span. I.e. one item is 2x1, another is 1x2 and a third is 1x1: https://codesandbox.io/s/dndkit-sortable-image-grid-forked-wmn92

I'm now facing two problems:

  • When dragging an item over and item of different size (i.e. drag a 2x2 item over and item that is 1x1) the item will be resized. I tried to change adjustScale on the DragOverlay from true to false but couldn't figure out any change in behaviour.
  • When dragging items so that a change in scroll behaviour occures (scroll -> no scroll) then there is a flickering and one is not able to correctly reorder. You can repro this by resizing the browser window in the CSB to approx. 900px height and then drag the show photo to the top left and then back to its original place.

Appreciate any pointers what I'm doing wrong/how to fix these problems.

Collision detection in sortable multi-containers with many items

Hi dnd master,

I'm trying to do something like this example with even more complexity within each columns (multi-level list...) but for the sake of this issue, the example is enough.

Describe the bug (Required)
When there is a lot of items in the first column (say A, so items are A1, A2...) and a very few in the second column (say B, with only B1 item), then a lot in the third column C, if you pick an item from A that is very down in the container, like A15 and try to put it in the B column, the A column or the C column scrolls up until the collision detect B1.

The more items you have in A and C, the more the bug is visible.

I assume the top property of the dragged item is causing this issue or something like this, I haven't jumped into the code but I guess.

Expected behavior (Required)
When picking A246, dragging over B1, want to be able to drop above or below B1 without waiting the scroll goes up :)

Maybe a collision "with the cursor position" would be great ? (I'm not aware of what is possible or not)

Thanks for the reading,
Cya

Are there plans to support touch events?

Hello,

This library seems very useful. Are there any plans to support touch events in the future? I think that would really help the adoption if you were able to support both HTML5 and touch seamlessly.

Cool library, looking forward to playing around with it.

Thanks,
-Todd

Wrong top calculation for scroll ancestors with fixed position?

Hi there, we're using the library to create a dnd experience between a scrollable fixed position div and a sortable ( scrollable ) drop zone.
This mostly works well ( we're currently using PR #54 as our basis ) but causes our DragOverlay to appear in the wrong top position after scrolling the drop zone.

Below is an example based on the sandbox shown in #43
scroll-fixed-3
https://codesandbox.io/s/react-dnd-grid-forked-gls5l?file=/src/App.js

We made a change to check whether an element ancestor is fixed in getScrollableAncestors, which causes only that ancestor to be returned ( Obviously, this is just a small demo and doesn't deal with more complex scenarios / performance etc.)

https://github.com/bbenzikry/dnd-kit/blob/a2cd7052c1cdf04e05af936127650b1dd6db7485/packages/core/src/utilities/scroll/getScrollableAncestors.ts#L22-L26

This makes the following return the expected value for our scenario

const scrollOffsets = getScrollOffsets(scrollableAncestors);
const top = offsetTop - scrollOffsets.y;

Resized dragged item loses position from cursor

I am trying to recreate the sortable grid with a large first tile example from Storybook and seeing an issue with dragging to and from the first item's position. It looks like the transform position of the dragged item is incorrect in relation to the user's cursor (see video below).

Example

See the code here:
https://codesandbox.io/s/ecstatic-pine-zs8nj?file=/src/SortableItem.jsx

Kapture.2021-01-07.at.14.37.19.mp4

Thanks for making such an intuitive drag and drop library, really excited to see this project progress!

Consider adding Clone from List example

A popular use-case for DnD is to drag Draggables from a static list to a Sortable Droppable as in a block-based page builder. Consider adding example to the Storybook to achieve this.

Nested DndContext not working

Hi,

I am using dndcontext and draggable component (say background component) to show panning effect, The nodes that sit on this background component have their own dnd context. The nodes are draggable by the handle. But the panning is triggered when I drag the body of the node. Due to which I am unable to resize the node.

Here is the sandbox link. https://codesandbox.io/s/crazy-antonelli-ubzm1
If you could take a quick look and advise if I am doing anything wrong or is it a bug.

How do we achieve nesting of nodes?

Is it possible to achieve nesting of nodes. Similar to react-dnd.

EX:

  • Boxes - Droppable / draggable
    • VeggieBox - Droppable / draggable
      • Carrots - Draggable
    • DairyBox - Droppable / draggable
      • Milk - Draggable

How do we achieve this?
Also would it be possible to integrate it with react-flow (https://github.com/wbkd/react-flow) Droppable & draggable as types of nodes.

Any help in this regard would be appreciated. Thanks

Using object array instead of a string array for id?

My sortable item has several props exposed such as title, category and image.

So instead of

[items, setItems] = useState(['1', '2', '3']);

My sortable item looks like:

[items, setItems] = useState([
{id: '1', title: 'x', category: 'y'},
{id: '2', title: 'z', category: 'w'}
...])

I am not sure how I can make this work.

Any help would be appreciated!

onClick handler for DndContext

Hi!

First of all, thanks for a great library!
I'm struggling with finding a good way to send onClick event to a draggable and sortable item - kind of works if I remove "onDragStart" prop and use only "onDragMove" to handle dragging but in that case the click needs to be quite precise. Looking for a way to handle clicking with a bit more buffer between click and dragMove.

Codesandbox here.

Difficult to manage drags across sections of the app

Example: I have a sortable list of items, but the user can also drag an item from the list into a completely different section of the app.

If I understand the docs correctly, Droppables will only recognize Draggables that are descendants of the same DnDContext. Since the sortable list is a deeply nested component that is far away from the area that I want the item to be dragged to, it means the DnDContext would have to be extremely high up in the component tree and managing the events of the DnDContext across the two distant components is more complicated than I would want. I would have to either propagate the events or use a notification type pattern or something like that.

Is there a way to link DnDContexts? So if I have my sortable list I could also register the items to be dropped into a distant DnDContext? Or am I totally structuring things incorrectly?

DndContext reducers all point to the same initial state variable, which is causing id collisions across nested and sibling providers

Hi, First of all, great job building this. It's an awesome library.

I am facing a problem with a use case where I have a nested structure. Can you please help resolve this?

I have a structure similar to the following:

<DndContext>
   <div>
        <Draggable />
        <Draggable />
        {/* multiple draggable items */}
    </div>

    <div>
          <Droppable>
             <DndContext>
                  <SortableContext>
                        <SortableItem />
                        <SortableItem />
                        {/* multiple sortable items */}
                  </SortableContext>
             </DndContext>
         </Droppable>

        <Droppable>
             <DndContext>
                  <SortableContext>
                        <SortableItem />
                        <SortableItem />
                        {/* multiple sortable items */}
                  </SortableContext>
             </DndContext>
         </Droppable>
         {/* Multiple similar droppable items */}
    </div>
</DndContext>

Now, I am able to move the draggable items to droppable zones. But the events are not being detected when trying to sort items in the individual droppable zones. I assume it is something related to event bubbling, but not sure. Any help in this regard will be appreciated. Thanks ๐Ÿ™

Codesandbox Link:
https://codesandbox.io/s/dnd-kit-gm09q?file=/src/App.js

Demo:
https://user-images.githubusercontent.com/17903466/104116991-a325a680-5343-11eb-96e0-469b168f83dd.mov

EDIT:
In the same codesandbox, add an empty section and try to add Page 12 to it before anything else. It isn't getting added. I don't know if I am missing something here.

DragOverlay does not work if element is in absolute position with a scaled container

When I use the DragOverlay inside a container (scaled), and the item has an absolute position inside it, the item replicated inside the drag overlay has the fixed position but with the left and top are taken from the original item (inside the scaled container).

Here is a repro example https://codesandbox.io/s/dnd-kit-scale-o69qm

This image shows the element that appears on click (bigger and shifted).
image

I tried to use adjustScale (but the provided scale inside the transform is 6 or 7 instead of 0.5) and other things. The only way to solve the problem was to add a modifier, force the scale, and add a transformation compensation, but I think it's a workaround.

Using getBoundingClientRect() I'm able to retrieve the correct coordinates with respect to the window, which I think should be used in this case to solve the problem.

Elements opacity is not being reset with multiple Draggable elements

Here is a codesandbox with the issue. If you have a single Draggable element, then the default animation associated with DragOverlay works fine. If you have multiple Draggable elements then the animation associated with DragOverlay is broken. It looks like it never resets to the original opacity. Not sure why.

https://codesandbox.io/s/intelligent-lake-uyimh?file=/src/App.js

Looks like these lines don't run

if (finalNode) {
finalNode.style.opacity = originalOpacity;
}

Anyway around this?

I mean you can get around this by setting the dropAnimation={null} in the DragOverlay (although that's not desired for my use-case).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.