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
 * This module provides change detection to forms, allowing a browser to warn the user before navigating away if changes
18
 * have been made.
19
 *
20
 * Two flags are stored for each form:
21
 * * a 'dirty' flag; and
22
 * * a 'submitted' flag.
23
 *
24
 * When the page is unloaded each watched form is checked. If the 'dirty' flag is set for any form, and the 'submitted'
25
 * flag is not set for any form, then a warning is shown.
26
 *
27
 * The 'dirty' flag is set when any form element is modified within a watched form.
28
 * The flag can also be set programatically. This may be required for custom form elements.
29
 *
30
 * It is not possible to customise the warning message in any modern browser.
31
 *
32
 * Please note that some browsers have controls on when these alerts may or may not be shown.
33
 * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload} for browser-specific
34
 * notes and references.
35
 *
36
 * @module     core_form/changechecker
37
 * @copyright  2021 Andrew Lyons <andrew@nicols.co.uk>
38
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39
 * @example <caption>Usage where the FormElement is already held</caption>
40
 *
41
 * import {watchForm} from 'core_form/changechecker';
42
 *
43
 * // Fetch the form element somehow.
44
 * watchForm(formElement);
45
 *
46
 * @example <caption>Usage from the child of a form - i.e. an input, button, div, etc.</caption>
47
 *
48
 * import {watchForm} from 'core_form/changechecker';
49
 *
50
 * // Watch the form by using a child of it.
51
 * watchForm(document.querySelector('input[data-foo="bar"]'););
52
 *
53
 * @example <caption>Usage from within a template</caption>
54
 * <form id="mod_example-entry-{{uniqid}}" ...>
55
 *   <!--
56
 *
57
 *   -->
58
 * </form>
59
 * {{#js}}
60
 * require(['core_form/changechecker'], function(changeChecker) {
61
 *     watchFormById('mod_example-entry-{{uniqid}}');
62
 * });
63
 * {{/js}}
64
 */
65
 
66
import {eventTypes} from 'core_editor/events';
67
import {getString} from 'core/str';
68
 
69
/**
70
 * @property {Bool} initialised Whether the change checker has been initialised
71
 * @private
72
 */
73
let initialised = false;
74
 
75
/**
76
 * @property {String} warningString The warning string to show on form change failure
77
 * @private
78
 */
79
let warningString;
80
 
81
/**
82
 * @property {Array} watchedForms The list of watched forms
83
 * @private
84
 */
85
let watchedForms = [];
86
 
87
/**
88
 * @property {Bool} formChangeCheckerDisabled Whether the form change checker has been actively disabled
89
 * @private
90
 */
91
let formChangeCheckerDisabled = false;
92
 
93
/**
94
 * Get the nearest form element from a child element.
95
 *
96
 * @param {HTMLElement} formChild
97
 * @returns {HTMLFormElement|null}
98
 * @private
99
 */
100
const getFormFromChild = formChild => formChild.closest('form');
101
 
102
/**
103
 * Watch the specified form for changes.
104
 *
105
 * @method
106
 * @param   {HTMLElement} formNode
107
 */
108
export const watchForm = formNode => {
109
    // Normalise the formNode.
110
    formNode = getFormFromChild(formNode);
111
 
112
    if (!formNode) {
113
         // No form found.
114
         return;
115
    }
116
 
117
    if (isWatchingForm(formNode)) {
118
        // This form is already watched.
119
        return;
120
    }
121
 
122
    watchedForms.push(formNode);
123
};
124
 
125
/**
126
 * Stop watching the specified form for changes.
127
 *
128
 * If the form was not watched, then no change is made.
129
 *
130
 * A child of the form may be passed instead.
131
 *
132
 * @method
133
 * @param   {HTMLElement} formNode
134
 * @example <caption>Stop watching a form for changes</caption>
135
 * import {unWatchForm} from 'core_form/changechecker';
136
 *
137
 * // ...
138
 * document.addEventListener('click', e => {
139
 *     if (e.target.closest('[data-action="changePage"]')) {
140
 *         unWatchForm(e.target);
141
 *     }
142
 * });
143
 */
144
export const unWatchForm = formNode => {
145
    watchedForms = watchedForms.filter(watchedForm => !!watchedForm.contains(formNode));
146
};
147
 
148
/**
149
 * Reset the 'dirty' flag for all watched forms.
150
 *
151
 * If a form was previously marked as 'dirty', then this flag will be cleared and when the page is unloaded no warning
152
 * will be shown.
153
 *
154
 * @method
155
 */
156
export const resetAllFormDirtyStates = () => {
157
    watchedForms.forEach(watchedForm => {
158
        watchedForm.dataset.formSubmitted = "false";
159
        watchedForm.dataset.formDirty = "false";
160
    });
161
};
162
 
163
/**
164
 * Reset the 'dirty' flag of the specified form.
165
 *
166
 * @method
167
 * @param   {HTMLElement} formNode
168
 */
169
export const resetFormDirtyState = formNode => {
170
    formNode = getFormFromChild(formNode);
171
 
172
    if (!formNode) {
173
         return;
174
    }
175
 
176
    formNode.dataset.formSubmitted = "false";
177
    formNode.dataset.formDirty = "false";
178
};
179
 
180
/**
181
 * Mark all forms as dirty.
182
 *
183
 * This function is only for backwards-compliance with the old YUI module and should not be used in any other situation.
184
 * It will be removed in Moodle 4.4.
185
 *
186
 * @method
187
 */
188
export const markAllFormsAsDirty = () => {
189
    watchedForms.forEach(watchedForm => {
190
        watchedForm.dataset.formDirty = "true";
191
    });
192
};
193
 
194
/**
195
 * Mark a specific form as dirty.
196
 *
197
 * This behaviour may be required for custom form elements which are not caught by the standard change listeners.
198
 *
199
 * @method
200
 * @param   {HTMLElement} formNode
201
 */
202
export const markFormAsDirty = formNode => {
203
    formNode = getFormFromChild(formNode);
204
 
205
    if (!formNode) {
206
         return;
207
    }
208
 
209
    // Mark it as dirty.
210
    formNode.dataset.formDirty = "true";
211
};
212
 
213
/**
214
 * Actively disable the form change checker.
215
 *
216
 * Please note that it cannot be re-enabled once disabled.
217
 *
218
 * @method
219
 */
220
export const disableAllChecks = () => {
221
    formChangeCheckerDisabled = true;
222
};
223
 
224
/**
225
 * Check whether any watched from is dirty.
226
 *
227
 * @method
228
 * @returns {Bool}
229
 */
230
export const isAnyWatchedFormDirty = () => {
231
    if (formChangeCheckerDisabled) {
232
        // The form change checker is disabled.
233
        return false;
234
    }
235
 
236
    const hasSubmittedForm = watchedForms.some(watchedForm => watchedForm.dataset.formSubmitted === "true");
237
    if (hasSubmittedForm) {
238
        // Do not warn about submitted forms, ever.
239
        return false;
240
    }
241
 
242
    const hasDirtyForm = watchedForms.some(watchedForm => {
243
        if (!watchedForm.isConnected) {
244
            // The watched form is not connected to the DOM.
245
            return false;
246
        }
247
 
248
        if (watchedForm.dataset.formDirty === "true") {
249
            // The form has been marked as dirty.
250
            return true;
251
        }
252
 
253
        // Elements currently holding focus will not have triggered change detection.
254
        // Check whether the value matches the original value upon form load.
255
        if (document.activeElement && document.activeElement.dataset.propertyIsEnumerable('initialValue')) {
256
            const isActiveElementWatched = isWatchingForm(document.activeElement)
257
                && !shouldIgnoreChangesForNode(document.activeElement);
258
            const hasValueChanged = document.activeElement.dataset.initialValue !== document.activeElement.value;
259
 
260
            if (isActiveElementWatched && hasValueChanged) {
261
                return true;
262
            }
263
        }
264
 
265
        return false;
266
    });
267
 
268
    if (hasDirtyForm) {
269
        // At least one form is dirty.
270
        return true;
271
    }
272
 
273
    // Handle TinyMCE editor instances.
274
    // TinyMCE forms may not have been initialised at the time that startWatching is called.
275
    // Check whether any tinyMCE editor is dirty.
276
    if (typeof window.tinyMCE !== 'undefined' && window.tinyMCE.editors) {
277
        if (window.tinyMCE.editors.some(editor => editor.isDirty())) {
278
            return true;
279
        }
280
    }
281
 
282
    // No dirty forms detected.
283
    return false;
284
};
285
 
286
/**
287
 * Get the watched form for the specified target.
288
 *
289
 * @method
290
 * @param   {HTMLNode} target
291
 * @returns {HTMLFormElement}
292
 * @private
293
 */
294
const getFormForNode = target => watchedForms.find(watchedForm => watchedForm.contains(target));
295
 
296
/**
297
 * Whether the specified target is a watched form.
298
 *
299
 * @method
300
 * @param   {HTMLNode} target
301
 * @returns {Bool}
302
 * @private
303
 */
304
const isWatchingForm = target => watchedForms.some(watchedForm => watchedForm.contains(target));
305
 
306
/**
307
 * Whether the specified target should ignore changes or not.
308
 *
309
 * @method
310
 * @param   {HTMLNode} target
311
 * @returns {Bool}
312
 * @private
313
 */
314
const shouldIgnoreChangesForNode = target => !!target.closest('.ignoredirty');
315
 
316
/**
317
 * Mark a form as changed.
318
 *
319
 * @method
320
 * @param   {HTMLElement} changedNode An element in the form which was changed
321
 */
322
export const markFormChangedFromNode = changedNode => {
323
    if (changedNode.dataset.formChangeCheckerOverride) {
324
        // Changes to this form node disable the form change checker entirely.
325
        // This is intended for select fields which cause an immediate redirect.
326
        disableAllChecks();
327
        return;
328
    }
329
 
330
    if (!isWatchingForm(changedNode)) {
331
        return;
332
    }
333
 
334
    if (shouldIgnoreChangesForNode(changedNode)) {
335
        return;
336
    }
337
 
338
    // Mark the form as dirty.
339
    const formNode = getFormForNode(changedNode);
340
    formNode.dataset.formDirty = "true";
341
};
342
 
343
/**
344
 * Mark a form as submitted.
345
 *
346
 * @method
347
 * @param   {HTMLElement} formNode An element in the form to mark as submitted
348
 */
349
export const markFormSubmitted = formNode => {
350
    formNode = getFormFromChild(formNode);
351
 
352
    if (!formNode) {
353
         return;
354
    }
355
 
356
    formNode.dataset.formSubmitted = "true";
357
};
358
 
359
/**
360
 * Mark all forms as submitted.
361
 *
362
 * This function is only for backwards-compliance with the old YUI module and should not be used in any other situation.
363
 * It will be removed in Moodle 4.4.
364
 *
365
 * @method
366
 */
367
export const markAllFormsSubmitted = () => {
368
    watchedForms.forEach(watchedForm => markFormSubmitted(watchedForm));
369
};
370
 
371
/**
372
 * Handle the beforeunload event.
373
 *
374
 * @method
375
 * @param   {Event} e
376
 * @returns {string|null}
377
 * @private
378
 */
379
const beforeUnloadHandler = e => {
380
    // Please note: The use of Promises in this function is forbidden.
381
    // This is an event handler and _cannot_ be asynchronous.
382
    let warnBeforeUnload = isAnyWatchedFormDirty() && !M.cfg.behatsiterunning;
383
    if (warnBeforeUnload) {
384
        // According to the specification, to show the confirmation dialog an event handler should call preventDefault()
385
        // on the event.
386
        e.preventDefault();
387
 
388
        // However note that not all browsers support this method, and some instead require the event handler to
389
        // implement one of two legacy methods:
390
        // * assigning a string to the event's returnValue property; and
391
        // * returning a string from the event handler.
392
 
393
        // Assigning a string to the event's returnValue property.
394
        e.returnValue = warningString;
395
 
396
        // Returning a string from the event handler.
397
        return e.returnValue;
398
    }
399
 
400
    // Attaching an event handler/listener to window or document's beforeunload event prevents browsers from using
401
    // in-memory page navigation caches, like Firefox's Back-Forward cache or WebKit's Page Cache.
402
    // Remove the handler.
403
    window.removeEventListener('beforeunload', beforeUnloadHandler);
404
 
405
    return null;
406
};
407
 
408
/**
409
 * Start watching for form changes.
410
 *
411
 * This function is called on module load, and should not normally be called.
412
 *
413
 * @method
414
 * @protected
415
 */
416
export const startWatching = () => {
417
    if (initialised) {
418
        return;
419
    }
420
 
421
    document.addEventListener('change', e => {
422
        if (!isWatchingForm(e.target)) {
423
            return;
424
        }
425
 
426
        markFormChangedFromNode(e.target);
427
    });
428
 
429
    document.addEventListener('click', e => {
430
        const ignoredButton = e.target.closest('[data-formchangechecker-ignore-submit]');
431
        if (!ignoredButton) {
432
            return;
433
        }
434
 
435
        const ownerForm = getFormFromChild(e.target);
436
        if (ownerForm) {
437
            ownerForm.dataset.ignoreSubmission = "true";
438
        }
439
    });
440
 
441
    document.addEventListener('focusin', e => {
442
        if (e.target.matches('input, textarea, select')) {
443
            if (e.target.dataset.propertyIsEnumerable('initialValue')) {
444
                // The initial value has already been set.
445
                return;
446
            }
447
            e.target.dataset.initialValue = e.target.value;
448
        }
449
    });
450
 
451
    document.addEventListener('submit', e => {
452
        const formNode = getFormFromChild(e.target);
453
        if (!formNode) {
454
            // Weird, but watch for this anyway.
455
            return;
456
        }
457
 
458
        if (formNode.dataset.ignoreSubmission) {
459
            // This form was submitted by a button which requested that the form checked should not mark it as submitted.
460
            formNode.dataset.ignoreSubmission = "false";
461
            return;
462
        }
463
 
464
        markFormSubmitted(formNode);
465
    });
466
 
467
    document.addEventListener(eventTypes.editorContentRestored, e => {
468
        if (e.target != document) {
469
            resetFormDirtyState(e.target);
470
        } else {
471
            resetAllFormDirtyStates();
472
        }
473
    });
474
 
475
    getString('changesmadereallygoaway', 'moodle')
476
    .then(changesMadeString => {
477
        warningString = changesMadeString;
478
        return;
479
    })
480
    .catch();
481
 
482
    window.addEventListener('beforeunload', beforeUnloadHandler);
483
};
484
 
485
/**
486
 * Watch the form matching the specified ID for changes.
487
 *
488
 * @method
489
 * @param   {String} formId
490
 */
491
export const watchFormById = formId => {
492
    watchForm(document.getElementById(formId));
493
};
494
 
495
/**
496
 * Reset the dirty state of the form matching the specified ID..
497
 *
498
 * @method
499
 * @param   {String} formId
500
 */
501
export const resetFormDirtyStateById = formId => {
502
    resetFormDirtyState(document.getElementById(formId));
503
};
504
 
505
/**
506
 * Mark the form matching the specified ID as dirty.
507
 *
508
 * @method
509
 * @param   {String} formId
510
 */
511
export const markFormAsDirtyById = formId => {
512
    markFormAsDirty(document.getElementById(formId));
513
};
514
 
515
// Configure all event listeners.
516
startWatching();