@neodrag/svelte

@neodrag/svelte

2.0.6 1.77KB

A lightweight Svelte Action to make your elements draggable.

pnpm add @neodrag/svelte

# or

bun install @neodrag/svelte

# or

npm install @neodrag/svelte

Migrating from svelte-drag

svelte-drag is the predecessor of this package. To migrate, follow the Migration guide

Usage

Basic usage

<script>
  import { draggable } from '@neodrag/svelte';
</script>

<div use:draggable>Hello</div>

With options

<script>
  import { draggable } from '@neodrag/svelte';
</script>

<div use:draggable={{ axis: 'x', grid: [10, 10] }}>Hello</div>

Defining options elsewhere with typescript

<script lang="ts">
  import { draggable } from '@neodrag/svelte';
  import type { DragOptions } from '@neodrag/svelte';

  let options: DragOptions = {
    axis: 'y',
    bounds: 'parent',
  };
</script>

<div use:draggable={options}>Hello</div>

Options

axis

Type: 'both' | 'x' | 'y' | 'none'
Default Value: 'both'

Axis on which the element can be dragged on. Valid values: both, x, y, none.

  • both - Element can move in any direction
  • x - Only horizontal movement possible
  • y - Only vertical movement possible
  • none - No movement at all
Both directions
0, 0
<div use:draggable={{ axis: 'both' }}>
  Both directions
</div>
Horizontal
0, 0
<div use:draggable={{ axis: 'x' }}>
  Horizontal
</div>
Vertical
0, 0
<div use:draggable={{ axis: 'y' }}>
  Vertical
</div>
None axis: Won't drag
0, 0
<div use:draggable={{ axis: 'none' }}>
  None axis: Won't drag
</div>

bounds

Type: HTMLElement | 'parent' | string | Partial<DragBoundsCoords>
Default Value: undefined

Optionally limit the drag area

parent: Limit to parent

Or, you can specify any selector and it will be bound to that.

Note: This library doesn’t check whether the selector is bigger than the node element. You yourself will have to make sure of that, or it may lead to unexpected behavior.

Or, finally, you can pass an object of type DragBoundsCoords. These mimic the css top, right, bottom and left, in the sense that bottom starts from the bottom of the window, and right from right of window. If any of these properties are unspecified, they are assumed to be 0.

export type DragBoundsCoords = {
  /** Number of pixels from left of the document */
  left: number;

  /** Number of pixels from top of the document */
  top: number;

  /** Number of pixels from the right side of document */
  right: number;

  /** Number of pixels from the bottom of the document */
  bottom: number;
};
Can't go outside the parent element
0, 0
<div use:draggable={{ bounds: 'parent' }}>
  Can't go outside the parent element
</div>
Can't go outside <body>
0, 0
<div use:draggable={{ bounds: 'body' }}>
  Can't go outside body
</div>
Limited to: top: 60
left: 20
bottom: 35
right: 30
Bounded by these coordinates from the window's edges.
0, 0
<div
  use:draggable={{
    bounds: { top: 60, left: 20, bottom: 35, right: 30 },
  }}
>
  Limited to:

  top: 60
  left: 20
  bottom: 35
  right: 30
</div>

recomputeBounds

Type: { dragStart?: boolean; drag?: boolean; dragEnd?: boolean; }
Default Value: { dragStart: true, drag: false, dragEnd: false }

When to recalculate the dimensions of the `bounds` element.

By default, bounds are recomputed only on dragStart. Use this options to change that behavior.

grid

Type: [number, number]
Default Value: undefined

Applies a grid on the page to which the element snaps to when dragging, rather than the default continuous grid.

If you’re programmatically creating the grid, do not set it to [0, 0] ever, that will stop drag at all. Set it to undefined to make it continuous once again

Snaps to 50x50 grid
0, 0
<div use:draggable={{ grid: [50, 50] }}>
  Snaps to 50x50 grid
</div>
Snaps to 72x91 grid
0, 0
<div use:draggable={{ grid: [72, 91] }}>
  Snaps to 72x91 grid
</div>
Snaps to 0x0 grid - Won't drag at all
0, 0
<div use:draggable={{ grid: [0, 0] }}>
  Snaps to 0x0 grid - Won't drag at all
</div>

defaultPosition

Type: { x: number; y: number }
Default Value: { x: 0, y: 0 }

Offsets your element to the position you specify in the very beginning. x and y should be in pixels. Ignored if position is passed.

Shifted by (100, 40)
100, 40
<div use:draggable={{ defaultPosition: { x: 100, y: 40 } }}>
  Shifted by (100, 40)
</div>

position

Type: { x: number; y: number }
Default Value: undefined

Controls the position of the element programmatically. Fully reactive.

Read about Controlled vs Uncontrolled components.

I can be moved with the slider too
X:    Y:
0, 0
<script>
  let position = { x: 0, y: 0 };
</script>

<div
  use:draggable={{
    position,
    onDrag: ({ offsetX, offsetY }) => {
      position = { x: offsetX, y: offsetY };
    },
  }}
>
  I can be moved with the slider too
</div>

X: <input type="range" min="0" max="300" bind:value={position.x} />
Y: <input type="range" min="0" max="300" bind:value={position.y} />
I can be moved only with the slider
X:    Y:
0, 0
<script>
  let position = { x: 0, y: 0 };
</script>

<div
  use:draggable={{
    position,
    disabled: true
  }}
>
  I can be moved with the slider too
</div>

X: <input type="range" min="0" max="300" bind:value={position.x} />
Y: <input type="range" min="0" max="300" bind:value={position.y} />

gpuAcceleration

Type: boolean
Default Value: true

If true, uses `translate3d` instead of `translate` to move the element around, and the hardware acceleration kicks in.

true by default, but can be set to false if blurry text issue occurs.

Depending on the device, you may not see much difference

GPU acceleration on
transform: translate3d(0px, 0px, 0)
<div use:draggable={{ gpuAcceleration: true }}>
  GPU acceleration on
</div>
GPU acceleration off
transform: translate(0px, 0px)
<div use:draggable={{ gpuAcceleration: false }}>
  GPU acceleration off
</div>

legacyTranslate

Type: boolean
Default Value: true

Whether to use the new translate property or transform: translate().

At the time of writing, translate property has less than 90% browsers availability. So, for now, this library will use the transform: translate() property to move the element. In future, when translate property will be more widely available, this library will switch to it by default. legacyTranslate’s default value will become false

Legacy translate with GPU acceleration
transform: translate3d(0px, 0px, 0)
<div use:draggable={{ legacyTranslate: true, gpuAcceleration: true }}>
  Legacy translate with GPU acceleration
</div>
Modern translate with GPU acceleration
translate: 0px 0px 1px
<div use:draggable={{ legacyTranslate: false, gpuAcceleration: true }}>
  Modern translate with GPU acceleration
</div>
Legacy translate with no GPU acceleration
transform: translate(0px, 0px)
<div use:draggable={{ legacyTranslate: true, gpuAcceleration: false }}>
  Legacy translate with no GPU acceleration
</div>
Modern translate with no GPU acceleration
translate: 0px 0px
<div use:draggable={{ legacyTranslate: false, gpuAcceleration: false }}>
  Modern translate with no GPU acceleration
</div>

transform

Type: ({ offsetX, offsetY, rootNode }: { offsetX: number; offsetY: number; rootNode: HTMLElement; }) => string | undefined | void
Default Value: undefined

Custom transform function. If provided, this function will be used to apply the DOM transformations to the root node to move it.

Existing transform logic, including gpuAcceleration and legacyTranslate, will be ignored. You can return a string to apply to a transform property, or not return anything and apply your transformations using rootNode.style.transform = VALUE

Moving by returning transform string
0, 0
<div
  use:draggable={{
    transform: ({ offsetX, offsetY }) => `translate(${offsetX + 50}px, ${offsetY + 20}px)`
  }}
>
  Moving by returning transform string
</div>
Moving by manually setting rootNode.style
0, 0
<div
  use:draggable={{
    transform: ({ offsetX, offsetY, rootNode }) => {
      rootNode.style.translate = `${offsetX + 50}px ${offsetY + 20}px`;
    },
  }}
>
  Moving by returning transform string
</div>

applyUserSelectHack

Type: boolean
Default Value: true

Applies user-select: none on <body /> element when dragging, to prevent the irritating effect where dragging doesn’t happen and the text is selected. Applied when dragging starts and removed when it stops.

User Select disabled
Hit ctrl + A while dragging - Nothing will be selected
0, 0
<div use:draggable={{ applyUserSelectHack: true }}>
  User Select disabled
</div>
User Select enabled
Hit ctrl + A while dragging - Text will be selected
0, 0
<div use:draggable={{ applyUserSelectHack: false }}>
  User Select enabled
</div>

ignoreMultitouch

Type: boolean
Default Value: true

Ignores touch events with more than 1 touch.

This helps when you have multiple elements on a canvas where you want to implement pinch-to-zoom behaviour.

Multi touch ignored
0, 0
<div use:draggable={{ ignoreMultitouch: true }}>
  Multi touch ignored
</div>
Multi touch allowed
0, 0
<div use:draggable={{ ignoreMultitouch: false }}>
  Multi touch allowed
</div>

disabled

Type: boolean
Default Value: false

Disables dragging.

Disabled. Won't drag, won't trigger any events
0, 0
<div use:draggable={{ disabled: true }}>
  Disabled. Won't drag, won't trigger any events
</div>

handle

Type: string | HTMLElement | HTMLElement[]
Default Value: undefined

CSS Selector of an element or multiple elements inside the parent node(on which use:draggable is applied). Can be an element or elements too. If it is provided, Only clicking and dragging on this element will allow the parent to drag, anywhere else on the parent won’t work.

Won't drag ❌

Drag me ✅
Single handle with selector
0, 0
<div use:draggable={{ handle: '.handle' }}>
  Won't drag ❌

  <div class="handle">Drag me ✅</div>
</div>
Won't drag ❌

Drag me ✅
Single handle with element
0, 0
<script lang="ts">
  let handleEl: HTMLDivElement;
</script>

<div use:draggable={{ handle: handleEl }}>
  Won't drag ❌

  <div bind:this={handleEl}>Drag me ✅</div>
</div>
Won't drag ❌

Drag me ✅
Drag me ✅
Multiple handle with selector
0, 0
<div use:draggable={{ handle: '.handle' }}>
  Won't drag ❌

  <div class="handle">Drag me ✅</div>
  <div class="handle">Drag me ✅</div>
</div>
Won't drag ❌

Drag me ✅
Drag me ✅
Multiple handle with element
0, 0
<script lang="ts">
  let handle1: HTMLDivElement;
  let handle2: HTMLDivElement;
</script>

<div use:draggable={{ handle: [handle1, handle2] }}>
  Won't drag ❌

  <div bind:this={handle1}>Drag me ✅</div>
  <div bind:this={handle2}>Drag me ✅</div>
</div>

cancel

Type: string | HTMLElement | HTMLElement[]
Default Value: undefined

CSS Selector of an element or multiple elements inside the parent node(on which use:draggable is applied). Can be an element or elements too. If it is provided, Trying to drag inside the cancel element(s) will prevent dragging.

This will drag!

This won't drag
Single cancel with selector
0, 0
<div use:draggable={{ cancel: '.cancel' }}>
  This will drag!

  <div class="cancel">This won't drag</div>
</div>
This will drag!

This won't drag
Single cancel passed as element.
0, 0
<script lang="ts">
  let cancelEl: HTMLElement;
</script>

<div use:draggable={{ cancel: cancelEl }}>
  This will drag!

  <div bind:this={cancelEl}>This won't drag</div>
</div>
This will drag!

This won't drag
This won't drag
Multiple cancel passed as element.
0, 0
<div use:draggable={{ cancel: '.cancel' }}>
  This will drag!

  <div class="cancel">This won't drag</div>
  <div class="cancel">This won't drag</div>
</div>
This will drag!

This won't drag
This won't drag
Multiple cancel passed as array of elements.
0, 0
<script lang="ts">
  let cancel1: HTMLDivElement;
  let cancel2: HTMLDivElement;
</script>

<div use:draggable={{ cancel: [cancel1, cancel2] }}>
  This will drag!

  <div bind:this={cancel1}>This won't drag</div>
  <div bind:this={cancel2}>This won't drag</div>
</div>

defaultClass

Type: string
Default Value: undefined

Class to apply to draggable element.

If handle is provided, it will still apply class on the parent element, NOT the handle.

defaultClassDragging

Type: string
Default Value: 'neodrag-dragging'

Class to apply on the parent element when it is dragging

defaultClassDragged

Type: string
Default Value: 'neodrag-dragged'

Class to apply on the parent element if it has been dragged at least once. Removed once dragging stops.

onDragStart

Type: (data: DragEventData) => void
Default Value: undefined

Fires when dragging start.

onDrag

Type: (data: DragEventData) => void
Default Value: undefined

Fires when dragging is going on.

onDragEnd

Type: (data: DragEventData) => void
Default Value: undefined

Fires when dragging stops.

Events

@neodrag/svelte emits 3 events, on:neodrag, on:neodrag:start & on:neodrag:end. These are all custom events, and can be listened on the node the use:draggable is applied to

Example:

<div
  use:draggable
  on:neodrag:start={(e) => console.log('Dragging started', e)}
  on:neodrag={(e) => console.log(e.detail)}
  on:neodrag:end={(e) => console.log('Dragging stopped', e)}
>
  Hello
</div>

Event signatures:

on:neodrag:start: (e: CustomEvent<DragEventData>) => void. Provides the initial offset when dragging starts, on the e.detail object.

on:neodrag:: (e: CustomEvent<DragEventData>. Provides how far the element has been dragged from it’s original position in x and y coordinates on the event.detail object

on:neodrag:end: (e: CustomEvent<DragEventData>) => void. No internal state provided to event.detail. Provides the final offset when dragging ends, on the e.detail object.

Alternative

If you scroll up, you’ll see 3 options, onDragStart, onDrag and onDragEnd. These are basically event handlers that you specify as methods of the options object.

Sometimes it helps to be able to put all your event listeners in one object and merge with that later on. To provide that ease of use, the events-as-objects exist.

How to use events-as-options? The syntax is similar to the custom events one 👇

<div
  use:draggable={{
    onDragStart: ({ offsetX, offsetY, rootNode, currentNode }) => {
      // Do something
    },
    onDrag: ({ offsetX, offsetY, rootNode, currentNode }) => {
      // Do something
    },
    onDragEnd: ({ offsetX, offsetY, rootNode, currentNode }) => {
      // Do something
    },

  }}
  class="box"
/>

Ultimately, this gives everyone a choice. non-TypeScript users will prefer the on:neodrag:* method because it is more idiomatic, and TypeScript users can go with events-as-options way to get better TS experience

Note: Do not use same event in two different ways. I.E., having on:neodrag:start and onDragStart at once will have both fire at the time when dragging starts. Use only one at a time.

If you’re a TypeScript user, read on below 👇

TypeScript

This library ships with proper TypeScript typings, for the best Developer Experience, whether authoring JS or TS.

Types Exported from package

This package exports these types you can use:

import type {
  DragAxis,
  DragBounds,
  DragBoundsCoords,
  DragOptions,
  DragEventData,
} from '@neodrag/svelte';

DragOptions is the documented list of all options provided by the component.

DragAxis is the type of axis option, and is equal to 'both' | 'x' | 'y' | 'none'.

DragBounds is 'parent' | string | Partial<DragBoundsCoords>, the complete type of bounds option.

DragBoundsCoords is when you’re specifying the bounds field using an object, this is the type needed for that.

DragEventData is the data provided during the events

export type DragAxis = 'both' | 'x' | 'y' | 'none';

export type DragBounds = 'parent' | string | Partial<DragBoundsCoords>;

export type DragEventData = {
  /** How much element moved from its original position horizontally */
  offsetX: number;

  /** How much element moved from its original position vertically */
  offsetY: number;

  /** The node on which the draggable is applied */
  rootNode: HTMLElement;

  /** The element being dragged */
  currentNode: HTMLElement;
};

export type DragBoundsCoords = {
  /** Number of pixels from left of the window */
  left: number;

  /** Number of pixels from top of the window */
  top: number;

  /** Number of pixels from the right side of window */
  right: number;

  /** Number of pixels from the bottom of the window */
  bottom: number;
};

Controlled vs Uncontrolled

This is taken straight from React’s philosophy(After all, this package is inspired from react-draggable).

Uncontrolled means your app doesn’t control the dragging of the app. Meaning, the user drags the element, it changes position, and you do something with that action. You yourself don’t change position of the element or anything. This is the default behavior of this library.

Controlled means your app, using state variables, changes the position of the element, or in simple terms, programmatically drag the element. You basically set the position property to { x: 10, y: 50 }(or any other numbers), and voila! yur now controlling the position of the element programmatically 🥳🥳

OFC, this library doesn’t go fully Controlled. The user can still drag it around even when position is set.

So, when you change position, the element position changes. However, when the element is dragged by user interaction, position is not changed. This is done intentionally, as two-way data binding here isn’t possible and also will lead to unexpected behavior. To keep the position variable up to date, use the on:neodrag event to keep your state up to date to the draggable’s internal state.

To have it be strictly Controlled, meaning it can only be moved programmatically, add the disabled option to your draggable element’s config

<div use:draggable={{ position: { x: 0, y: 10 }, disabled: true }} />

Credits

Inspired from the amazing react-draggable library, and implements the same API.