sortable_controller.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { Controller } from "@hotwired/stimulus";
  2. import Sortable from 'sortablejs'
  3. export default class extends Controller {
  4. connect() {
  5. this.sortable = Sortable.create(this.element, {
  6. group: 'shared',
  7. sort: this.data.get('sortable') ?? false,
  8. filter: '.title',
  9. onEnd: this.end.bind(this)
  10. });
  11. }
  12. end(event) {
  13. const filmId = event.item.dataset.id;
  14. const fromList = event.from.classList.contains('user-list') ? 'user' : 'common';
  15. const toList = event.to.classList.contains('user-list') ? 'user' : 'common';
  16. const oldIndex = event.oldIndex
  17. const newIndex = event.newIndex
  18. const order = this.sortable.toArray();
  19. console.log(oldIndex, newIndex)
  20. console.log(order)
  21. fetch(this.data.get('url'), {
  22. method: 'POST',
  23. headers: {
  24. 'Content-Type': 'application/json'
  25. },
  26. body: JSON.stringify({ filmId: filmId, fromList: fromList, toList: toList, oldIndex: oldIndex, newIndex: newIndex, order: order })
  27. })
  28. .then(response => response.json())
  29. .then(data => {
  30. if(data.success) {
  31. console.log('Liste updated successfully');
  32. } else {
  33. console.error('Failed to update list');
  34. }
  35. })
  36. .catch(error => {
  37. console.error('Error:', error);
  38. });
  39. ;
  40. }
  41. }