Sortable

์ด ์˜ˆ์ œ์—์„œ๋Š” Sortable ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ htmx์™€ ํ†ตํ•ฉํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค.

๋จผ์ €, Sortable ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ .sortable ํด๋ž˜์Šค๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค:

htmx.onLoad(function(content) {
    var sortables = content.querySelectorAll(".sortable");
    for (var i = 0; i < sortables.length; i++) {
      var sortable = sortables[i];
      var sortableInstance = new Sortable(sortable, {
          animation: 150,
          ghostClass: 'blue-background-class',

          // `.htmx-indicator`๋ฅผ ์ •๋ ฌ ๋ถˆ๊ฐ€๋Šฅํ•˜๊ฒŒ ๋งŒ๋“ญ๋‹ˆ๋‹ค.
          filter: ".htmx-indicator",
          onMove: function (evt) {
            return evt.related.className.indexOf('htmx-indicator') === -1;
          },

          // `end` ์ด๋ฒคํŠธ ์‹œ ์ •๋ ฌ์„ ๋น„ํ™œ์„ฑํ™”ํ•ฉ๋‹ˆ๋‹ค.
          onEnd: function (evt) {
            this.option("disabled", true);
          }
      });

      // `htmx:afterSwap` ์ด๋ฒคํŠธ์—์„œ ์ •๋ ฌ์„ ๋‹ค์‹œ ํ™œ์„ฑํ™”ํ•ฉ๋‹ˆ๋‹ค.
      sortable.addEventListener("htmx:afterSwap", function() {
        sortableInstance.option("disabled", false);
      });
    }
})

๋‹ค์Œ์œผ๋กœ, ๋‚ด๋ถ€์— ์ •๋ ฌ ๊ฐ€๋Šฅํ•œ div๋“ค์ด ์žˆ๋Š” ํผ์„ ์ƒ์„ฑํ•˜๊ณ , Sortable.js์˜ end ์ด๋ฒคํŠธ์—์„œ ajax ์š”์ฒญ์„ ํŠธ๋ฆฌ๊ฑฐํ•ฉ๋‹ˆ๋‹ค:

<form class="sortable" hx-post="/items" hx-trigger="end">
  <div class="htmx-indicator">Updating...</div>
  <div><input type='hidden' name='item' value='1'/>Item 1</div>
  <div><input type='hidden' name='item' value='2'/>Item 2</div>
  <div><input type='hidden' name='item' value='3'/>Item 3</div>
  <div><input type='hidden' name='item' value='4'/>Item 4</div>
  <div><input type='hidden' name='item' value='5'/>Item 5</div>
</form>

๊ฐ div์—๋Š” ํ•ด๋‹น ํ–‰์˜ ํ•ญ๋ชฉ ID๋ฅผ ์ง€์ •ํ•˜๋Š” ์ˆจ๊ฒจ์ง„ input์ด ํฌํ•จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.

Sortable.js ๋“œ๋ž˜๊ทธ ์•ค ๋“œ๋กญ์œผ๋กœ ๋ชฉ๋ก์ด ์žฌ์ •๋ ฌ๋˜๋ฉด end ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. htmx๋Š” ์ƒˆ๋กœ์šด ์ˆœ์„œ์˜ ํ•ญ๋ชฉ ID๋“ค์„ /items๋กœ POSTํ•˜์—ฌ ์„œ๋ฒ„์— ์ €์žฅํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

์ด๊ฒŒ ์ „๋ถ€์ž…๋‹ˆ๋‹ค!

Server Requests ↑ Show

๐Ÿ”—Demo