Skip to content

Commit 0b6c92b

Browse files
committed
refac
1 parent 64ec736 commit 0b6c92b

1 file changed

Lines changed: 29 additions & 9 deletions

File tree

src/lib/components/admin/Settings/Models/ModelList.svelte

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<script lang="ts">
22
import Sortable from 'sortablejs';
33
4-
import { createEventDispatcher, getContext, onMount } from 'svelte';
4+
import { createEventDispatcher, getContext, onDestroy, onMount, tick } from 'svelte';
55
const i18n = getContext('i18n');
66
77
import { models } from '$lib/stores';
@@ -14,20 +14,27 @@
1414
let modelListElement = null;
1515
1616
const positionChangeHandler = () => {
17-
const modelList = Array.from(modelListElement.children).map((child) =>
17+
// Read new order from DOM
18+
const newOrder = Array.from(modelListElement.children).map((child) =>
1819
child.id.replace('model-item-', '')
1920
);
2021
21-
modelIds = modelList;
22-
};
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+
}
2329
24-
$: if (modelIds) {
25-
init();
26-
}
30+
// Update reactive data — Svelte will re-render with the new order
31+
modelIds = newOrder;
32+
};
2733
28-
const init = () => {
34+
const initSortable = () => {
2935
if (sortable) {
3036
sortable.destroy();
37+
sortable = null;
3138
}
3239
3340
if (modelListElement) {
@@ -40,11 +47,24 @@
4047
});
4148
}
4249
};
50+
51+
onMount(() => {
52+
// Wait a tick for the {#if} block to render and bind modelListElement
53+
tick().then(() => {
54+
initSortable();
55+
});
56+
});
57+
58+
onDestroy(() => {
59+
if (sortable) {
60+
sortable.destroy();
61+
}
62+
});
4363
</script>
4464

4565
{#if modelIds.length > 0}
4666
<div class="flex flex-col -translate-x-1" bind:this={modelListElement}>
47-
{#each modelIds as modelId, modelIdx (`${modelId}-${modelIdx}`)}
67+
{#each modelIds as modelId (modelId)}
4868
<div class=" flex gap-2 w-full justify-between items-center" id="model-item-{modelId}">
4969
<Tooltip content={modelId} placement="top-start">
5070
<div class="flex items-center gap-1">

0 commit comments

Comments
 (0)