|
| 1 | +<script lang="ts"> |
| 2 | + import { draggable, droppable, type DragDropState } from '$lib/index.js'; |
| 3 | +
|
| 4 | + interface Item { |
| 5 | + id: string; |
| 6 | + title: string; |
| 7 | + } |
| 8 | +
|
| 9 | + let items = $state<Item[]>([ |
| 10 | + { id: '1', title: 'This list is interactive' }, |
| 11 | + { id: '2', title: 'You can drag and drop items' }, |
| 12 | + { id: '3', title: 'You can also select items' }, |
| 13 | + { id: '4', title: 'You can also delete items' } |
| 14 | + ]); |
| 15 | +
|
| 16 | + function handleDelete(id: string) { |
| 17 | + items = items.filter((item) => item.id !== id); |
| 18 | + } |
| 19 | +
|
| 20 | + function handleSelect(id: string) { |
| 21 | + console.log('Selected item:', id); |
| 22 | + alert('Selected item: ' + id); |
| 23 | + } |
| 24 | +
|
| 25 | + function handleDrop(state: DragDropState<Item>) { |
| 26 | + const { draggedItem, sourceContainer, targetContainer } = state; |
| 27 | + if (!targetContainer || sourceContainer === targetContainer) return; |
| 28 | +
|
| 29 | + const sourceIndex = items.findIndex((item) => item.id === draggedItem.id); |
| 30 | + const targetIndex = parseInt(targetContainer); |
| 31 | +
|
| 32 | + const [movedItem] = items.splice(sourceIndex, 1); |
| 33 | + items.splice(targetIndex, 0, movedItem); |
| 34 | + items = [...items]; // Force reactivity |
| 35 | + } |
| 36 | +</script> |
| 37 | + |
| 38 | +<div class="container mx-auto p-8"> |
| 39 | + <div class="mb-8 flex flex-col gap-2"> |
| 40 | + <h1 class="text-2xl font-bold">Interactive Draggable List</h1> |
| 41 | + <p class="text-gray-600"> |
| 42 | + Try clicking the items or delete buttons while also being able to drag and reorder the list. |
| 43 | + </p> |
| 44 | + </div> |
| 45 | + |
| 46 | + <div class="space-y-2"> |
| 47 | + {#each items as item, index (item.id)} |
| 48 | + <div |
| 49 | + use:droppable={{ |
| 50 | + container: index.toString(), |
| 51 | + callbacks: { |
| 52 | + onDrop: handleDrop |
| 53 | + } |
| 54 | + }} |
| 55 | + use:draggable={{ |
| 56 | + container: index.toString(), |
| 57 | + dragData: item, |
| 58 | + interactive: ['[data-delete-btn]', '[data-select-btn]', '.interactive'] |
| 59 | + }} |
| 60 | + class="flex items-center justify-between rounded-lg bg-white p-4 shadow transition-all hover:shadow-md" |
| 61 | + > |
| 62 | + <button |
| 63 | + data-select-btn |
| 64 | + class="interactive flex-1 text-left hover:text-blue-600" |
| 65 | + onclick={() => handleSelect(item.id)} |
| 66 | + > |
| 67 | + {item.title} |
| 68 | + </button> |
| 69 | + |
| 70 | + <button |
| 71 | + data-delete-btn |
| 72 | + class="ml-2 text-red-500 hover:text-red-700" |
| 73 | + onclick={() => handleDelete(item.id)} |
| 74 | + > |
| 75 | + Delete |
| 76 | + </button> |
| 77 | + </div> |
| 78 | + {/each} |
| 79 | + </div> |
| 80 | +</div> |
0 commit comments