2 * JavaScript for Special:Preferences: Enable save button and prevent the window being accidentally
3 * closed when any form field is changed.
7 var allowCloseWindow
, saveButton
, restoreButton
;
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
,
18 for ( index
= 0; index
< inputs
.length
; index
++ ) {
19 input
= inputs
[ index
];
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
) {
31 } else if ( $input
.is( 'input' ) || $input
.is( 'textarea' ) ) {
32 // <input> has defaultValue or defaultChecked
33 inputType
= input
.type
;
34 if ( inputType
=== 'radio' || inputType
=== 'checkbox' ) {
35 if ( input
.checked
!== input
.defaultChecked
) {
38 } else if ( input
.value
!== input
.defaultValue
) {
47 saveButton
= OO
.ui
.infuse( $( '#prefcontrol' ) );
48 restoreButton
= OO
.ui
.infuse( $( '#mw-prefs-restoreprefs' ) );
50 // Disable the button to save preferences unless preferences have changed
51 // Check if preferences have been changed before JS has finished loading
52 saveButton
.setDisabled( !isPrefsChanged() );
53 // Attach capturing event handlers to the document, to catch events inside OOUI dropdowns:
54 // * Use capture because OO.ui.SelectWidget also does, and it stops event propagation,
55 // so the event is not fired on descendant elements
56 // * Attach to the document because the dropdowns are in the .oo-ui-defaultOverlay element
57 // (and it doesn't exist yet at this point, so we can't attach them to it)
58 [ 'change', 'keyup', 'mouseup' ].forEach( function ( eventType
) {
59 document
.addEventListener( eventType
, function () {
60 // Make sure SelectWidget's event handlers run first
61 setTimeout( function () {
62 saveButton
.setDisabled( !isPrefsChanged() );
67 // Set up a message to notify users if they try to leave the page without
69 allowCloseWindow
= mw
.confirmCloseWindow( {
71 message
: mw
.msg( 'prefswarning-warning', mw
.msg( 'saveprefs' ) ),
72 namespace: 'prefswarning'
74 $( '#mw-prefs-form' ).on( 'submit', allowCloseWindow
.release
);
75 restoreButton
.on( 'click', function () {
76 allowCloseWindow
.release();
77 // The default behavior of events in OOUI is always prevented. Follow the link manually.
78 // Note that middle-click etc. still works, as it doesn't emit a OOUI 'click' event.
79 location
.href
= restoreButton
.getHref();