summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/batch-select.js
blob: 340fc680ec405618cd8dc1e59c7464f3c06fe888 (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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import { $, $$, showEl, hideEl, onGlobalLeftClick } from './utils/dom';
import {fetchJson, handleError} from "./utils/requests";

const selectedIds = [];
let batchSelecting = false;

const updateStatus = (el, text) => {
    $('span', el).textContent = text;
};

const markSelected = (elem) => {
    elem.classList.remove('media-box__header--unselected');
    elem.classList.add('media-box__header--selected');
};

const markUnselected = (elem) => {
    elem.classList.remove('media-box__header--selected');
    elem.classList.add('media-box__header--unselected');
};

const unmark = (elem) => {
    elem.classList.remove('media-box__header--selected');
    elem.classList.remove('media-box__header--unselected');
};

const saveSelectedIds = () => {
    localStorage.setItem('batch-select-ids', JSON.stringify([...selectedIds]));
};

const updateDom = () => {
    $$('.media-box__header').forEach(markUnselected);

    for (const postId of selectedIds) {
        $$(`.media-box[data-post-id="${postId}"] > .media-box__header`).forEach(markSelected);
    }
};

const onImageClicked = (elem) => {
    if (!batchSelecting) {
        return true;
    }

    const header = elem.querySelector('.media-box__header');
    const postId = elem.dataset.postId;

    if (selectedIds.indexOf(postId) !== -1) {
        selectedIds.splice(selectedIds.indexOf(postId), 1)
        markUnselected(header);
    } else {
        selectedIds.push(postId);
        markSelected(header);
    }

    saveSelectedIds();

    return false;
};

const beginBatchSelect = () => {
    hideEl($('.js-batch-select'));
    showEl($('.js-batch-select-abort'), $('.js-batch-select-tag'), $('.js-batch-select-delete'));
    updateDom();

    batchSelecting = true;

    return false;
};

const abortBatchSelect = () => {
    selectedIds.splice(0, selectedIds.length);
    localStorage.removeItem('batch-select-ids');
    hideEl($('.js-batch-select-abort'), $('.js-batch-select-tag'), $('.js-batch-select-delete'));
    $$('.media-box__header').forEach(unmark);
    showEl($('.js-batch-select'));


    batchSelecting = false;

    $('.js-batch-select-tag > span').innerText = 'Tag';
    $('.js-batch-select-delete > span').innerText = 'Delete';


    return false;
};

const submitBatchTag = (el) => {
    const tagString = prompt('Enter a comma-separated list of tags to add (-tag to remove): ');

    if (tagString === null || tagString === '') {
        return false;
    }

    updateStatus(el, 'Wait...');

    fetchJson('PUT', '/admin/batch/tags', {
        tags: tagString,
        post_ids: selectedIds,
    })
        .then(handleError)
        .then(r => r.json())
        .then(data => {
            if (data.failed.length) window.alert(`Failed to add tags to the images with these IDs: ${data.failed}`);
            else window.alert(`Successfully tagged ${data.succeeded.length} posts.`);
            abortBatchSelect();
        });

    return false;
};

const submitBatchDeletion = (el) => {
    const deletionReason = prompt('Enter deletion reason (hit cancel or leave blank to cancel): ');

    if (deletionReason === null || deletionReason === '') {
        return false;
    }

    updateStatus(el, 'Wait...');

    fetchJson('DELETE', '/admin/batch/posts', {
        deletion_reason: deletionReason,
        post_ids: selectedIds,
    })
        .then(handleError)
        .then(r => r.json())
        .then(data => {
            if (data.failed.length) window.alert(`Failed to delete the posts with these IDs: ${data.failed}`);
            else window.alert(`Successfully deleted ${data.succeeded.length} posts.`);

            abortBatchSelect();
        });
}

const setupBatchSelect = () => {
    const localStorageData = localStorage.getItem('batch-select-ids');

    if (localStorageData !== null) {
        for (const postId of JSON.parse(localStorageData)) {
            selectedIds.push(postId);
        }

        beginBatchSelect();
    }

    const targets = {
        '.js-batch-select': beginBatchSelect,
        '.js-batch-select-abort': abortBatchSelect,
        '.js-batch-select-tag': submitBatchTag,
        '.js-batch-select-delete': submitBatchDeletion,
        '.media-box': onImageClicked
    };

    onGlobalLeftClick(targets);
};

export { setupBatchSelect };