anseki / plain-draggable

The simple and high performance library to allow HTML/SVG element to be dragged.
https://anseki.github.io/plain-draggable/
MIT License
765 stars 96 forks source link

passing data to snap #95

Closed tawjaw closed 3 years ago

tawjaw commented 3 years ago

Hello,

Is there a way I can pass data to snap points and retrieve it when the element is snapped.

For example:

const snapPoints = [
{x: 0, y: 0, id: 1},
{x: 100, y: 100, id: 2},
]

const start = new this.PlainDraggable(this.$refs.start,{

      onDrag: function(pos){
        if(pos.snapped)
        {
           //HERE be able to access the id. something like 
          //   pos.snapped.id
        }
      },

      snap: snapPoints
    });

this would be much easier to find out which point is snapped instead of comparing position.

anseki commented 3 years ago

Hi @tawjaw, thank you for the comment. This may help you: https://github.com/anseki/plain-draggable/issues/78#issuecomment-881807380

tawjaw commented 3 years ago

thanks @anseki I've seen this.

but it seems a bit inefficient to me this way.

Would you be open to modifying the library a bit and allowing a meta data value to be passed with every snap target? and be able to retrieve it in onDrag

the snap target array would look something like this

const snapPoints = [
{x: 0, y: 0, meta: {...}},
{x: 100, y: 100, meta:{...}},
]

and here I can get the meta data

onDrag: function(pos){
        if(pos.snapped)
        {
           //get pos.meta
        }
      },

I think the modification would be simple, unfortunately I wasn't successful doing it.

I think you just need to make copies of the meta into all expanded snap targets. and then somewhere here https://github.com/anseki/plain-draggable/blob/8b9d755f85418efc387260423db456145712bdb8/src/plain-draggable.js#L1845 you'd pass the meta from the snap target to the return.

position.snappedMeta = activeProps.snapTargets[snappedIndex].meta; 

this way I don't have to go through all the snap targets at every little step. I can access it in O(1) by passing an ID to meta.

Thanks for your help!

anseki commented 3 years ago

I think that the changing should not be applied because that breaks the library and it has low demand. However, of course you can fork it and change that for your app. I recommend the way to get the index because it is easy and it is efficient in usual cases.

tawjaw commented 3 years ago

thanks @anseki I'll work with the way you suggested for now. If I find I need a more efficient solution, I'll fork and modify.

Thanks

anseki commented 3 years ago

:smile: