Drag and Drop

The drag and drop interaction provides a way to drag and drop content, such as elements or files, from one location to another.

Example

Drag a product into your basket

๐Ÿฅ‘
๐ŸŸ

Sources

+page.svelte

<script lang="ts">
  import Basket from './Basket.svelte'
  import Product from './Product.svelte'

  const products = ['๐Ÿง€', '๐Ÿงด', '๐Ÿชฅ', '๐Ÿฅ‘', '๐Ÿฅ–', 'โ˜•', '๐Ÿบ', '๐Ÿ…', '๐ŸŸ']
</script>

<div class="mb-4 flex w-fit flex-wrap gap-2 rounded">
  {#each products as value}
    <Product {value} />
  {/each}
</div>

<p class="mb-2 text-xs opacity-50">Drag a product into your basket</p>
<Basket items={['๐Ÿฅ‘', '๐ŸŸ']} />

Basket.svelte

<script lang="ts">
  import { useDrop } from 'louisette'

  export let items: string[] = []

  const { drop, hovering } = useDrop({
    onDrop: (event) => {
      const item = event.dataTransfer.getData('text/plain')
      items = [...items, item]
    },
  })
</script>

<div
  use:drop
  class="mb-2 flex min-h-[3rem] w-full flex-wrap gap-2 rounded-md border-2 border-transparent bg-amber-50 p-2 shadow dark:bg-amber-950"
  class:is-hovering={$hovering}
>
  {#each items as item}
    <div class="select-none p-1">{item}</div>
  {/each}
</div>

<style lang="postcss">
  .is-hovering {
    @apply border-dashed border-amber-500 transition-colors;
  }
</style>

Product.svelte

<script lang="ts">
  import { useDrag } from 'louisette'

  export let value: string

  const { dragging, drag, draggableAttrs } = useDrag()
</script>

<button
  use:drag={value}
  {...$draggableAttrs}
  class="rounded border-2 border-transparent p-2 transition-colors transition-opacity hover:bg-neutral-200 dark:hover:bg-neutral-700"
  class:is-dragging={$dragging}
>
  {value}
</button>

<style lang="postcss">
  .is-dragging {
    @apply border-amber-500 opacity-50;
  }
</style>