Merge "Add string length limits"
[lhc/web/wiklou.git] / resources / src / mediawiki.special / mediawiki.special.preferences.confirmClose.js
1 /*!
2 * JavaScript for Special:Preferences: Enable save button and prevent the window being accidentally
3 * closed when any form field is changed.
4 */
5 ( function ( mw, $ ) {
6 $( function () {
7 var allowCloseWindow, saveButton, restoreButton;
8
9 // Check if all of the form values are unchanged.
10 // (This function could be changed to infuse and check OOUI widgets, but that would only make it
11 // slower and more complicated. It works fine to treat them as HTML elements.)
12 function isPrefsChanged() {
13 var inputs = $( '#mw-prefs-form :input[name]' ),
14 input, $input, inputType,
15 index, optIndex,
16 opt;
17
18 for ( index = 0; index < inputs.length; index++ ) {
19 input = inputs[ index ];
20 $input = $( input );
21
22 // Different types of inputs have different methods for accessing defaults
23 if ( $input.is( 'select' ) ) {
24 // <select> has the property defaultSelected for each option
25 for ( optIndex = 0; optIndex < input.options.length; optIndex++ ) {
26 opt = input.options[ optIndex ];
27 if ( opt.selected !== opt.defaultSelected ) {
28 return true;
29 }
30 }
31 } else if ( $input.is( 'input' ) ) { // <input> has defaultValue or defaultChecked
32 inputType = input.type;
33 if ( inputType === 'radio' || inputType === 'checkbox' ) {
34 if ( input.checked !== input.defaultChecked ) {
35 return true;
36 }
37 } else if ( input.value !== input.defaultValue ) {
38 return true;
39 }
40 }
41 }
42
43 return false;
44 }
45
46 saveButton = OO.ui.infuse( $( '#prefcontrol' ) );
47 restoreButton = OO.ui.infuse( $( '#mw-prefs-restoreprefs' ) );
48
49 // Disable the button to save preferences unless preferences have changed
50 // Check if preferences have been changed before JS has finished loading
51 if ( !isPrefsChanged() ) {
52 saveButton.setDisabled( true );
53 $( '#preferences .oo-ui-fieldsetLayout' ).one( 'change keydown mousedown', function () {
54 saveButton.setDisabled( false );
55 } );
56 }
57
58 // Set up a message to notify users if they try to leave the page without
59 // saving.
60 allowCloseWindow = mw.confirmCloseWindow( {
61 test: isPrefsChanged,
62 message: mw.msg( 'prefswarning-warning', mw.msg( 'saveprefs' ) ),
63 namespace: 'prefswarning'
64 } );
65 $( '#mw-prefs-form' ).submit( $.proxy( allowCloseWindow, 'release' ) );
66 restoreButton.on( 'click', function () {
67 allowCloseWindow.release();
68 // The default behavior of events in OOUI is always prevented. Follow the link manually.
69 // Note that middle-click etc. still works, as it doesn't emit a OOUI 'click' event.
70 location.href = restoreButton.getHref();
71 } );
72 } );
73 }( mediaWiki, jQuery ) );