sortable_controller.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. delay: 500, // time in milliseconds to define when the sorting should start
  10. delayOnTouchOnly: true,
  11. onEnd: this.end.bind(this)
  12. });
  13. }
  14. end(event) {
  15. const filmId = event.item.dataset.id;
  16. const fromList = event.from.classList.contains('user-list') ? 'user' : 'common';
  17. const toList = event.to.classList.contains('user-list') ? 'user' : 'common';
  18. const oldIndex = event.oldIndex
  19. const newIndex = event.newIndex
  20. const order = this.sortable.toArray();
  21. console.log(oldIndex, newIndex)
  22. console.log(order)
  23. fetch(this.data.get('url'), {
  24. method: 'POST',
  25. headers: {
  26. 'Content-Type': 'application/json'
  27. },
  28. body: JSON.stringify({ filmId: filmId, fromList: fromList, toList: toList, oldIndex: oldIndex, newIndex: newIndex, order: order })
  29. })
  30. .then(response => response.json())
  31. .then(data => {
  32. if(data.success) {
  33. console.log('Liste updated successfully');
  34. } else {
  35. console.error('Failed to update list');
  36. }
  37. })
  38. .catch(error => {
  39. console.error('Error:', error);
  40. });
  41. ;
  42. }
  43. }