Giter Site home page Giter Site logo

tahash / swapy Goto Github PK

View Code? Open in Web Editor NEW
2.7K 6.0 45.0 236 KB

✨ A framework-agnostic tool that converts any layout into a drag-to-swap one with just a few lines of code https://swapy.tahazsh.com/

License: MIT License

TypeScript 96.88% JavaScript 3.12%

swapy's Introduction

swapy's People

Contributors

tahash avatar niko7o avatar

Stargazers

 avatar Mortensen Cristian avatar Joost Schuur avatar Kasper Andreassen avatar  avatar Brandon Bennett avatar Alexey Bolisov avatar Dmytro Zhyvonitko avatar Phillip Beazley avatar Andrew Lee avatar Aditya Pandey avatar  avatar Maxime Goyette avatar Rob Gordon avatar OussamaBernou avatar yuvals1 avatar Antonis Ntoulis avatar Rex Ng avatar Solomon ogu avatar Gareth avatar  avatar Chris Bolton avatar Adam Jones avatar Abhishek Pathak avatar Lars Væhrens avatar Andrew avatar Gereon Doerner avatar Jared Prather avatar Brian avatar alBz avatar Lukas Krüdewagen avatar Tomi Ruusala avatar Mahmood Bagheri avatar Frank avatar McLOVIN avatar Felipe avatar sandipkurmi avatar Anil Seervi avatar Dale Inverarity avatar Lmekki HAMDANI avatar Tri Vo Khac avatar Patryk Błaziński avatar Maurício Braz avatar Dirk avatar Jeffrey Munowitch avatar Urs Hanselmann avatar Mike avatar Jeet Mandaliya avatar Mike Sindani avatar mzudse avatar Sven avatar Justin Rhoades avatar Nicolas Charpentier avatar Diego Gomes avatar  avatar Mahesh Bishnoi avatar Alin Osan avatar AMR YASSER avatar Roman Almazov avatar Den Marty avatar  avatar Vinícius Moraes avatar Dan Cristino avatar waru avatar EVOKE avatar Ryan Lay avatar Juliaan avatar Mateusz Lewko avatar Daniel J. Kim avatar LeeKrane avatar Tyrus Malmström avatar Tanjim Hossain avatar Anit Sarkar avatar Carl-Christian Hänsel avatar Nikhil avatar Lahiru Amarasooriya avatar Eyas Valdez avatar Lucas O'Connell avatar Jeremy Feng avatar Renaldo Mateus avatar Methawi Phokhai avatar ashley avatar Aayush Shah avatar Dmitrii Kuzmin avatar Revaz Goguadze avatar George Thomas avatar Foxi avatar AJ avatar Antoine Bagnaud avatar René Herrmann avatar  avatar  avatar Victor avatar Dennis Torres avatar Gabe Santos avatar Panaintescu Adrian avatar Abd El Rahman Zeid avatar akazwz avatar We1337 avatar Himateja avatar

Watchers

Kryspin Ziemski avatar  avatar Alin Osan avatar exinfinite avatar Stanley Stephen avatar  avatar

swapy's Issues

Items flickering when using multiple containers

My code:

export default function Test() {
  useEffect(() => {
    const container = document.querySelector(".swapy-container");
    const container2 = document.querySelector(".swapy-container2");
    const container3 = document.querySelector(".swapy-container3");

    createSwapy(container, {
      animation: "dynamic", // or spring or none
    });

    createSwapy(container2, {
      animation: "dynamic", // or spring or none
    });

    createSwapy(container3, {
      animation: "dynamic", // or spring or none
    });
  }, []);

  return (
    <div className="flex flex-col gap-16 py-32">
      <div className="swapy-container space-y-4">
        <div data-swapy-slot="foo" className="bg-red-500/20 p-4">
          <div data-swapy-item="a">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              FOO
            </div>
          </div>
        </div>

        <div data-swapy-slot="bar" className="bg-red-500/20 p-4">
          <div data-swapy-item="b">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              BAR
            </div>
          </div>
        </div>

        <div data-swapy-slot="baz" className="bg-red-500/20 p-4">
          <div data-swapy-item="c">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              BAZ
            </div>
          </div>
        </div>
      </div>

      <div className="swapy-container2 space-y-4">
        <div data-swapy-slot="foo1" className="bg-red-500/20 p-4">
          <div data-swapy-item="a1">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              FOO 1
            </div>
          </div>
        </div>

        <div data-swapy-slot="bar1" className="bg-red-500/20 p-4">
          <div data-swapy-item="b1">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              BAR 1
            </div>
          </div>
        </div>

        <div data-swapy-slot="baz1" className="bg-red-500/20 p-4">
          <div data-swapy-item="c1">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              BAZ 1
            </div>
          </div>
        </div>
      </div>

      <div className="swapy-container3 space-y-4">
        <div data-swapy-slot="foo2" className="bg-red-500/20 p-4">
          <div data-swapy-item="a2">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              FOO 2
            </div>
          </div>
        </div>

        <div data-swapy-slot="bar2" className="bg-red-500/20 p-4">
          <div data-swapy-item="b2">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              BAR 2
            </div>
          </div>
        </div>

        <div data-swapy-slot="baz2" className="bg-red-500/20 p-4">
          <div data-swapy-item="c2">
            <div className="relative flex h-full w-full items-center justify-center rounded-[10px] bg-red-400 font-bold">
              BAZ 2
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Apparently this occurs only if you scroll down/up the page

capture.mp4

Question: why do we need two different divs for slot and item

Why do we need to pass two different ids for the same item ?
i mean slot and item. since each slot must have only one item, so better to generate this internally or avoid it instead!

Also would be better to create a react component like SwapyProvider and SwapyItem

Provider should be a context and have onSwap.
Item should take id, and children

Dynamic slots and items issue

When working with dynamic slots and items, there are inconsistencies and swapy doesn't work, seems like it requires slots to be put at the moment of initialisation. Also there is no way to remove swapy from attached to element, I think adding this would make a temporary solution, that will reinitialise swapy on items change

TypeScript issue: createSwapy ~ Argument of type 'Element | null' is not assignable to parameter of type 'Element'

Hey dude! Minor fix that could probably make a 0.0.6 patch release.

Context

Argument of type 'Element | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2345)

Opened a small PR fixing it here after testing it:
#5

Reason

The document.querySelector method used in the instancing logic does not always return an Element. If no elements are found on the DOM with the desired selector, it will return null and we need the type to support that. A quick example in the Chrome Console:

image

Screenshots

image

GIF

error on adding new slots

Hi,
Great job. It is really powerful and easy to use.
I am trying to add new slots with javascript but I get an error.

swapy

Is there an workaround?
Thanks

Enable API throw an error

I tried to debug it, but locally is minified and I just didn't have much time to dig into your plugin lifecycle.

version: 0.0.5

The following code:

this.swapy = createSwapy(propertiesContainer);
this.swapy.enable(true);

Throws:

Error: You can't call getPlugin for Swapy with key: undefined because it does not exist in your app

Secondary drag appears to start from original spot

This will be a hard to one to describe in text.

When dropped into existing code, upon swapping an image the second time, the image is picked up from it's original spot but the cursor drop zone remains legitimate. So, everything still functions, but it's very disorienting.

<div id="thumbnailsGrid">
  <picture class="thumb photo$idx PhotoLab photoMarkup $host $mode" data-swapy-slot="slot$idx">
    <div data-swapy-item="item$idx">
      <img src="example.jpg"/>
      <div data-swapy-handle></div>
    </div>
  </picture>
</div>

Has anyone experience this before?

https://i.imgur.com/9osCgkZ.mp4

Feature Request: Option to Swap Only Initial and Final Positions

Hello,

Firstly, I'd like to thank you for developing and maintaining this fantastic library. It has significantly simplified the implementation of drag-to-swap functionality in my projects.

Issue:

Currently, the library moves every element between the initial and final positions when an element is dragged and dropped. However, in my use case, I need an option to swap only the initial and final positions, without affecting the intermediate elements. This feature would provide greater flexibility and control over the layout behavior during drag-and-drop operations.

Example:

Here's an illustration of the current behavior and the desired behavior:

Current Behavior:

Initial: [A, B, C, D, E]
Drag 'A' to position of 'D'
Result: [B, C, D, A, E]
Desired Behavior:

Initial: [A, B, C, D, E]
Drag 'A' to position of 'D'
Result: [D, B, C, A, E]
Proposal:

I propose adding an option or method to enable swapping only the initial and final positions of the dragged element. This could be a configuration setting or a specific method call.

Benefits:

Enhanced flexibility for different use cases.
Greater control over the layout behavior during drag-and-drop.
More intuitive behavior for certain user interfaces.
Additional Context:

If needed, I can assist with testing the new feature or providing further examples of how this functionality could be utilized.

Thank you for considering this feature request. I look forward to your response and am hopeful that this can be incorporated into the library.

Best regards,

Danivalldo

docs: Add example with next.js

What is the best way to use swapy with next.js?

  • Make container a client component and the slots and content server components
  • Make container and slots client components and the content server component.

Adding an example would be nice.

Elements added later in a React project cannot be dragged and dropped

My code is here

useEffect(() => {
const tempContainer = document.querySelector('.graphGroupContainer')!;
    const swapy = createSwapy(tempContainer, {
      animation: 'dynamic', // or spring or none
    });
    // You can disable and enable it anytime you want
    swapy.enable(true);
}, []);


......



{graphGroup.map((item, index) => {
  return (
      <div
          className={` w-[49.8%] flex flex-col text-center px-[20px] pb-[1rem] mb-[5px]`}
          key={`${item.name}-${index}`}
          data-swapy-slot={`${item.id}`}
      >
        <div data-swapy-item={item.name} className={`bg-[white]`}>
        </div>
      </div>
  );
})} 

then i found the item what is added later dont have the same property like the initialValue.
cc4f895a943af916587e4f8f89167eb

I try to rebuild swapy instance when the graphGroup had change:

useEffect(() => {
    if (graphGroup.length > 0) {
      gentSwapy();
    }
  }, [graphGroup]);

  const gentSwapy = () => {
    const tempContainer = document.querySelector('.graphGroupContainer')!;
    const swapy = createSwapy(tempContainer, {
      animation: 'dynamic', // or spring or none
    });
    // You can disable and enable it anytime you want
    swapy.enable(true);
  };

and i got same plugin-id,so much so that it still can't be dragged.

image

Is there any good workaround?
I didn't find the documentation for the elements added later.

Thank you so much

Docs: Add an example in Javascript

Hello there!
It would be fantastic if we have an example of how to use Swapy in Javascript to use it as fast as it possible, like we have in examples/basic.

What do you think about it?

The elements are flickering and malfunctioning

Epic Privacy Browser Version 120.0.6099.71 (Official Build) (32-bit)

When I open the page, the blocks on the demo dashboard are shaking and flickering. These shakes get bigger and bigger until they take up the whole screen and more. If I try to move the blocks, things get even weirder. I've attached a video to show you.
screen-capture.webm

Needs reference documentation

Thanks for this tool. It seems great. However I can't seem to find a simple reference of all methods and properties supported. This would be very handy. Probably a necessity that seems to be missing.

That said, the console error messages were great for getting things up and running.

Deep override

No matter how deep DOM is, they all get swapy attributes
I have a case of showing blocks with background with style attribute that just gets overwriten by swapy
Screenshot 2024-07-22 at 00 53 29

Screen.Recording.2024-07-22.at.00.55.59.mov

code like this

<div
      className="item"
      data-swapy-item={itemId}
    >
      <div>
        <span>
          <span>
            <span>
              <span>
                <span
                  className="w-8 h-8 rounded-md bg-slate-50 inline-block"
                  style={{
                    backgroundColor: colour,
                  }}
                ></span>
              </span>
            </span>
          </span>
          {/* {colour} */}
        </span>
      </div>
    </div>

is same as this for swapy

    <div className="item" data-swapy-item={itemId}>
      <div>
        <span
          className="w-8 h-8 rounded-md bg-slate-50 inline-block"
          style={{
            backgroundColor: colour,
          }}
        ></span>
      </div>
    </div>

Wierd behavior with image item

I've noticed that behavior whenever slot-item has a full image

<div
      data-swapy-slot={'1'}
      className={className}
    >
      <div
        data-swapy-item={`1-1`}
        className="w-full h-full flex items-center justify-center"
      >
        <img
            src="https://images.unsplash.com/photo-1722716202526-10f3d3ed8f12?q=80&w=3387&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
            className={'w-full h-full object-cover'}
            alt="image"
          />
      </div>
    </div>

Performance degradation on resize

First of all awesome project insane how easy this is to do now!

Issue

I have noticed that when working with (possibly excessively) large components that performance significantly degrades on page resize. This cannot be fixed by setting animation: 'none' on createSwapy.

It works (mostly) fine albeit slightly slower than normal use without resizing, unfortunately if you are using something like Arc Browser where you are constantly opening and closing the sidebar the performance degradation on resize is quite noticeable.

I am not sure if this could be fixed with allowing animation: 'none' to also apply to resize animations.

Repro

I created a repro for this in SvelteKit here.

I understand if this ends up being closed as not planned or otherwise dismissed because this may just be one of those 'Don't do that' situations.

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.