summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/galleries.js
blob: db67ecc2d817d391d9e21d7ad22c5fe4935838bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
 * Gallery rearrangement.
 */

import { arraysEqual } from './utils/array';
import { $, $$ } from './utils/dom';
import { initDraggables } from './utils/draggable';
import { fetchJson } from './utils/requests';

export function setupGalleryEditing() {
  if (!$('.rearrange-button')) return;

  const [ rearrangeEl, saveEl ] = $$('.rearrange-button');
  const sortableEl = $('#sortable');
  const containerEl = $('.post-grid');

  // Copy array
  let oldImages = window.booru.galleryImages.slice();
  let newImages = window.booru.galleryImages.slice();

  initDraggables();

  $$('.media-box', containerEl).forEach(i => i.draggable = true);

  rearrangeEl.addEventListener('click', () => {
    sortableEl.classList.add('editing');
    containerEl.classList.add('drag-container');
  });

  saveEl.addEventListener('click', () => {
    sortableEl.classList.remove('editing');
    containerEl.classList.remove('drag-container');

    newImages = $$('.image-container', containerEl).map(i => parseInt(i.dataset.postId, 10));

    // If nothing changed, don't bother.
    if (arraysEqual(newImages, oldImages)) return;

    fetchJson('PATCH', saveEl.dataset.reorderPath, {
      image_ids: newImages,

    // copy the array again so that we have the newly updated set
    }).then(() => oldImages = newImages.slice());
  });
}