From 0095b11b1b4d53c7f3e3670833c685d5ed8cbd87 Mon Sep 17 00:00:00 2001 From: Katja Lutz Date: Wed, 22 Jun 2022 21:28:01 +0200 Subject: [PATCH] feat: implement sortable directive --- src/directives/sortable.tsx | 74 +++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/directives/sortable.tsx diff --git a/src/directives/sortable.tsx b/src/directives/sortable.tsx new file mode 100644 index 0000000..b1dab0d --- /dev/null +++ b/src/directives/sortable.tsx @@ -0,0 +1,74 @@ +import { onCleanup, onMount } from "solid-js"; +import Sortable from "sortablejs"; + +// https://github.com/SortableJS/Sortable + +export const sortable = (el: HTMLElement, config: () => any) => { + onMount(function () { + const config_ = config(); + + const userOnEnd = config_?.onEnd; + if (userOnEnd) { + config_.onEnd = (evt) => { + const parent = evt.from; + const oldNextSibling = + parent.children[evt.oldIndex + (evt.oldIndex > evt.newIndex ? 1 : 0)]; + if (oldNextSibling) { + parent.insertBefore(evt.item, oldNextSibling); + } else { + parent.append(evt.item); + } + + userOnEnd(evt); + }; + } + + const sortable = Sortable.create(el, config_); + + onCleanup(function () { + sortable.destroy(); + }); + }); +}; + +declare module "solid-js" { + namespace JSX { + interface Directives { + sortable: any; + } + } +} + +/* +let sortableDiv: HTMLDivElement = undefined; +onMount(function () { + const sortable = Sortable.create(sortableDiv, { + dragClass: "sortable-drag-card", + ghostClass: "sortable-ghost-card", + filter: ".drag-disabled", + forceFallback: true, + onEnd: (evt) => { + const parent = evt.from; + const oldNextSibling = + parent.children[evt.oldIndex + (evt.oldIndex > evt.newIndex ? 1 : 0)]; + if (oldNextSibling) { + parent.insertBefore(evt.item, oldNextSibling); + } else { + parent.append(evt.item); + } + + setPositions( + produce((positions: any[]) => { + let item = positions[evt.oldIndex]; + positions.splice(evt.oldIndex, 1); + positions.splice(evt.newIndex, 0, unwrap(item)); + }) + ); + }, + }); + + onCleanup(function () { + sortable.destroy(); + }); +}); +*/