<script>
import Sortable from 'sortablejs';
import { BROWSER } from 'esm-env'; // Ensure code only runs in browser
let items = $state(['Item 1', 'Item 2', 'Item 3']); // Svelte 5 state with Runes
function sortable(node, options) {
let sortableInstance;
if (BROWSER) { // Only run initialization in the browser
sortableInstance = Sortable.create(node, {
animation: 150,
ghostClass: 'blue-background-class', // Example class
...options, // Pass any options from the component
onEnd: (event) => {
// Logic to reorder the 'items' array based on event.oldIndex and event.newIndex
const itemMoved = items.splice(event.oldIndex, 1)[0];
items.splice(event.newIndex, 0, itemMoved);
// Because 'items' is a $state variable, Svelte 5 automatically detects the change
// If you passed a callback: options.onSortEnd(newOrder);
// If dispatching event: node.dispatchEvent(new CustomEvent('sorted', { detail: { oldIndex: event.oldIndex, newIndex: event.newIndex }}));
},
});
}
return {
// Optional: Update SortableJS options if parameters change
update(newOptions) {
if (sortableInstance && BROWSER) {
// Update options if needed, check SortableJS docs
// sortableInstance.option('...', newOptions.someValue);
}
},
destroy() {
if (sortableInstance && BROWSER) {
sortableInstance.destroy(); // Clean up
}
}
};
}
</script>
<!-- Use the action on the container -->
<ul use:sortable>
{#each items as item (item)} <!-- Use key for proper list updates -->
<li>{item}</li>
{/each}
</ul>
<style>
li { padding: 10px; border: 1px solid #ccc; margin-bottom: 5px; cursor: grab; }
.blue-background-class { background-color: lightblue; opacity: 0.7; }
</style>