Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * Javascript handling for HTML attributes. This module gets autoloaded on page load.
18
 *
19
 * With the appropriate HTML attributes, various functionalities defined in this module can be used such as a displaying
20
 * an alert or a confirmation modal, etc.
21
 *
22
 * @module     core/utility
23
 * @copyright  2021 Andrew Nicols <andrew@nicols.co.uk>
24
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25
 * @since      4.0
26
 *
27
 * @example <caption>Calling the confirmation modal to delete a block</caption>
28
 *
29
 * // The following is an example of how to use this module via an indirect PHP call with a button.
30
 *
31
 * $controls[] = new action_menu_link_secondary(
32
 *     $deleteactionurl,
33
 *     new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')),
34
 *     $str,
35
 *     [
36
 *         'class' => 'editing_delete',
37
 *         'data-modal' => 'confirmation', // Needed so this module will pick it up in the click handler.
38
 *         'data-modal-title-str' => json_encode(['deletecheck_modal', 'block']),
39
 *         'data-modal-content-str' => json_encode(['deleteblockcheck', 'block', $blocktitle]),
40
 *         'data-modal-yes-button-str' => json_encode(['delete', 'core']),
41
 *         'data-modal-toast' => 'true', // Can be set to inform the user that their action was a success.
42
 *         'data-modal-toast-confirmation-str' => json_encode(['deleteblockinprogress', 'block', $blocktitle]),
43
 *         'data-modal-destination' => $deleteconfirmationurl->out(false), // Where do you want to direct the user?
44
 *     ]
45
 * );
46
 */
47
 
48
import * as Str from 'core/str';
49
import Pending from 'core/pending';
50
import {add as addToast} from 'core/toast';
51
import {saveCancelPromise, deleteCancelPromise, exception} from 'core/notification';
52
 
53
// We want to ensure that we only initialize the listeners only once.
54
let registered = false;
55
 
56
/**
57
 * Either fetch the string or return it from the dom node.
58
 *
59
 * @method getConfirmationString
60
 * @private
61
 * @param {HTMLElement} dataset The page element to fetch dataset items in
62
 * @param {String} type The type of string to fetch
63
 * @param {String} field The dataset field name to fetch the contents of
64
 * @param {Array|null} [defaultValue=null] The default params to pass to get_string if no value is found in a dataset
65
 * @return {Promise}
66
 *
67
 */
68
const getModalString = (dataset, type, field, defaultValue = null) => {
69
    if (dataset[`${type}${field}Str`]) {
70
        return Str.get_string.apply(null, JSON.parse(dataset[`${type}${field}Str`]));
71
    }
72
    if (dataset[`${type}${field}`]) {
73
        return Promise.resolve(dataset[`${type}${field}`]);
74
    }
75
 
76
    if (defaultValue) {
77
        return Str.get_string.apply(null, defaultValue);
78
    }
79
 
80
    return null;
81
};
82
 
83
/**
84
 * Display a save/cancel confirmation.
85
 *
86
 * @private
87
 * @param {HTMLElement} source The title of the confirmation
88
 * @param {String} type The content of the confirmation
89
 * @returns {Promise}
90
 */
91
const displayConfirmation = (source, type) => {
92
    let confirmationPromise = null;
93
    if (`${type}Type` in source.dataset && source.dataset[`${type}Type`] === 'delete') {
94
        confirmationPromise = deleteCancelPromise(
95
            getModalString(source.dataset, type, 'Title', ['confirm', 'core']),
96
            getModalString(source.dataset, type, 'Content'),
97
            getModalString(source.dataset, type, 'YesButton', ['yes', 'core'])
98
        );
99
    } else {
100
        confirmationPromise = saveCancelPromise(
101
            getModalString(source.dataset, type, 'Title', ['confirm', 'core']),
102
            getModalString(source.dataset, type, 'Content'),
103
            getModalString(source.dataset, type, 'YesButton', ['yes', 'core'])
104
        );
105
    }
106
    return confirmationPromise.then(() => {
107
        if (source.dataset[`${type}Toast`] === 'true') {
108
            const stringForToast = getModalString(source.dataset, type, 'ToastConfirmation');
109
            if (typeof stringForToast === "string") {
110
                addToast(stringForToast);
111
            } else {
112
                stringForToast.then(str => addToast(str)).catch(e => exception(e));
113
            }
114
        }
115
 
116
        if (source.dataset[`${type}Destination`]) {
117
            window.location.href = source.dataset[`${type}Destination`];
118
            return;
119
        }
120
 
121
        if (source.closest('form')) {
122
            // Update the modal and confirmation data fields so that we don't loop.
123
            source.dataset.confirmation = 'none';
124
            source.dataset.modal = 'none';
125
 
126
            // Click on the button again.
127
            // Note: Do not use the form.submit() because it will not work for cancel buttons.
128
            source.click();
129
            return;
130
        }
131
 
132
        const link = source.closest('a');
133
        if (link && link.href && link.href !== '#') {
134
            window.location.href = link.href;
135
            return;
136
        }
137
 
138
        const button = source.closest('button, input[type="submit"], input[type="button"], input[type="reset"]');
139
        if (button) {
140
            source.dataset.modalSubmitting = true;
141
            source.click();
142
            return;
143
        }
144
 
145
        window.console.error(`No destination found for ${type} modal`);
146
        return;
147
    }).catch(() => {
148
        return;
149
    });
150
};
151
 
152
/**
153
 * Display an alert and return the promise from it.
154
 *
155
 * @private
156
 * @param {String} title The title of the alert
157
 * @param {String} body The content of the alert
158
 * @returns {Promise<ModalAlert>}
159
 */
160
const displayAlert = async(title, body) => {
161
    const pendingPromise = new Pending('core/confirm:alert');
162
    const AlertModal = await import('core/local/modal/alert');
163
 
164
    return AlertModal.create({
165
        title,
166
        body,
167
        removeOnClose: true,
168
        show: true,
169
    })
170
    .then((modal) => {
171
        pendingPromise.resolve();
172
        return modal;
173
    });
174
};
175
 
176
/**
177
 * Set up the listeners for the confirmation modal widget within the page.
178
 *
179
 * @method registerConfirmationListeners
180
 * @private
181
 */
182
const registerConfirmationListeners = () => {
183
    document.addEventListener('click', e => {
184
        if (e.target.closest('[data-modal-submitting]')) {
185
            return;
186
        }
187
        const confirmRequest = e.target.closest('[data-confirmation="modal"]');
188
        if (confirmRequest) {
189
            e.preventDefault();
190
            displayConfirmation(confirmRequest, 'confirmation');
191
        }
192
 
193
        const modalConfirmation = e.target.closest('[data-modal="confirmation"]');
194
        if (modalConfirmation) {
195
            e.preventDefault();
196
            displayConfirmation(modalConfirmation, 'modal');
197
        }
198
 
199
        const alertRequest = e.target.closest('[data-modal="alert"]');
200
        if (alertRequest) {
201
            e.preventDefault();
202
            displayAlert(
203
                getModalString(alertRequest.dataset, 'modal', 'Title'),
204
                getModalString(alertRequest.dataset, 'modal', 'Content'),
205
            );
206
        }
207
    });
208
};
209
 
210
if (!registered) {
211
    registerConfirmationListeners();
212
    registered = true;
213
}