|
1 | 1 | <script lang="ts"> |
2 | 2 | import Sortable from 'sortablejs'; |
3 | 3 |
|
4 | | - import { createEventDispatcher, getContext, onDestroy, onMount, tick } from 'svelte'; |
| 4 | + import { createEventDispatcher, getContext, onMount, onDestroy, tick } from 'svelte'; |
5 | 5 | const i18n = getContext('i18n'); |
6 | 6 |
|
7 | 7 | import { models } from '$lib/stores'; |
|
13 | 13 | let sortable = null; |
14 | 14 | let modelListElement = null; |
15 | 15 |
|
16 | | - const positionChangeHandler = () => { |
17 | | - // Read new order from DOM |
18 | | - const newOrder = Array.from(modelListElement.children).map((child) => |
19 | | - child.id.replace('model-item-', '') |
20 | | - ); |
| 16 | + const positionChangeHandler = (event) => { |
| 17 | + const { oldIndex, newIndex, item } = event; |
21 | 18 |
|
22 | | - // Revert SortableJS DOM manipulation so Svelte stays in control of the DOM |
23 | | - if (sortable) { |
24 | | - sortable.sort( |
25 | | - modelIds.map((id) => `model-item-${id}`), |
26 | | - true |
27 | | - ); |
28 | | - } |
| 19 | + // Revert SortableJS's DOM manipulation so Svelte doesn't get out of sync. |
| 20 | + // Svelte expects the DOM to match its virtual DOM before it applies state updates. |
| 21 | + const parent = item.parentNode; |
| 22 | + const target = parent.children[oldIndex < newIndex ? oldIndex : oldIndex + 1]; |
| 23 | + parent.insertBefore(item, target); |
29 | 24 |
|
30 | | - // Update reactive data — Svelte will re-render with the new order |
31 | | - modelIds = newOrder; |
| 25 | + // Now apply the logical state update, letting Svelte handle the real DOM move. |
| 26 | + const updatedIds = [...modelIds]; |
| 27 | + const [movedId] = updatedIds.splice(oldIndex, 1); |
| 28 | + updatedIds.splice(newIndex, 0, movedId); |
| 29 | + modelIds = updatedIds; |
32 | 30 | }; |
33 | 31 |
|
34 | 32 | const initSortable = () => { |
|
41 | 39 | sortable = new Sortable(modelListElement, { |
42 | 40 | animation: 150, |
43 | 41 | handle: '.model-item-handle', |
44 | | - onUpdate: async (event) => { |
45 | | - positionChangeHandler(); |
| 42 | + onUpdate: (event) => { |
| 43 | + positionChangeHandler(event); |
46 | 44 | } |
47 | 45 | }); |
48 | 46 | } |
49 | 47 | }; |
50 | 48 |
|
| 49 | + $: if (modelIds && modelListElement) { |
| 50 | + tick().then(() => { |
| 51 | + initSortable(); |
| 52 | + }); |
| 53 | + } |
| 54 | +
|
51 | 55 | onMount(() => { |
52 | | - // Wait a tick for the {#if} block to render and bind modelListElement |
53 | 56 | tick().then(() => { |
54 | 57 | initSortable(); |
55 | 58 | }); |
|
0 commit comments