Ignore name-less inputs on preference page confirmCloseWindow check
[lhc/web/wiklou.git] / resources / src / mediawiki.special / mediawiki.special.preferences.js
1 /*!
2 * JavaScript for Special:Preferences
3 */
4 ( function ( mw, $ ) {
5 $( function () {
6 var $preftoc, $preferences, $fieldsets,
7 labelFunc,
8 $tzSelect, $tzTextbox, $localtimeHolder, servertime,
9 allowCloseWindow, notif;
10
11 labelFunc = function () {
12 return this.id.replace( /^mw-prefsection/g, 'preftab' );
13 };
14
15 $( '#prefsubmit' ).attr( 'id', 'prefcontrol' );
16 $preftoc = $( '#preftoc' );
17 $preferences = $( '#preferences' );
18
19 $fieldsets = $preferences.children( 'fieldset' )
20 .attr( {
21 role: 'tabpanel',
22 'aria-labelledby': labelFunc
23 } );
24 $fieldsets.not( '#mw-prefsection-personal' )
25 .hide()
26 .attr( 'aria-hidden', 'true' );
27
28 // T115692: The following is kept for backwards compatibility with older skins
29 $preferences.addClass( 'jsprefs' );
30 $fieldsets.addClass( 'prefsection' );
31 $fieldsets.children( 'legend' ).addClass( 'mainLegend' );
32
33 // Make sure the accessibility tip is selectable so that screen reader users take notice,
34 // but hide it per default to reduce interface clutter. Also make sure it becomes visible
35 // when selected. Similar to jquery.mw-jump
36 $( '<div>' ).addClass( 'mw-navigation-hint' )
37 .text( mw.msg( 'prefs-tabs-navigation-hint' ) )
38 .attr( 'tabIndex', 0 )
39 .on( 'focus blur', function ( e ) {
40 if ( e.type === 'blur' || e.type === 'focusout' ) {
41 $( this ).css( 'height', '0' );
42 } else {
43 $( this ).css( 'height', 'auto' );
44 }
45 } ).insertBefore( $preftoc );
46
47 /**
48 * It uses document.getElementById for security reasons (HTML injections in $()).
49 *
50 * @ignore
51 * @param {string} name the name of a tab without the prefix ("mw-prefsection-")
52 * @param {string} [mode] A hash will be set according to the current
53 * open section. Set mode 'noHash' to surpress this.
54 */
55 function switchPrefTab( name, mode ) {
56 var $tab, scrollTop;
57 // Handle hash manually to prevent jumping,
58 // therefore save and restore scrollTop to prevent jumping.
59 scrollTop = $( window ).scrollTop();
60 if ( mode !== 'noHash' ) {
61 location.hash = '#mw-prefsection-' + name;
62 }
63 $( window ).scrollTop( scrollTop );
64
65 $preftoc.find( 'li' ).removeClass( 'selected' )
66 .find( 'a' ).attr( {
67 tabIndex: -1,
68 'aria-selected': 'false'
69 } );
70
71 $tab = $( document.getElementById( 'preftab-' + name ) );
72 if ( $tab.length ) {
73 $tab.attr( {
74 tabIndex: 0,
75 'aria-selected': 'true'
76 } )
77 .focus()
78 .parent().addClass( 'selected' );
79
80 $preferences.children( 'fieldset' ).hide().attr( 'aria-hidden', 'true' );
81 $( document.getElementById( 'mw-prefsection-' + name ) ).show().attr( 'aria-hidden', 'false' );
82 }
83 }
84
85 // Check for messageboxes (.successbox, .warningbox, .errorbox) to replace with notifications
86 if ( $( '.mw-preferences-messagebox' ).length ) {
87 // If there is a #mw-preferences-success box and javascript is enabled, use a slick notification instead!
88 if ( $( '#mw-preferences-success' ).length ) {
89 notif = mw.notification.notify( mw.message( 'savedprefs' ), { autoHide: false } );
90 // 'change' event not reliable!
91 $( '#preftoc, .prefsection' ).one( 'change keydown mousedown', function () {
92 if ( notif ) {
93 notif.close();
94 notif = null;
95 }
96 } );
97 }
98 }
99
100 // Enable keyboard users to use left and right keys to switch tabs
101 $preftoc.on( 'keydown', function ( event ) {
102 var keyLeft = 37,
103 keyRight = 39,
104 $el;
105
106 if ( event.keyCode === keyLeft ) {
107 $el = $( '#preftoc li.selected' ).prev().find( 'a' );
108 } else if ( event.keyCode === keyRight ) {
109 $el = $( '#preftoc li.selected' ).next().find( 'a' );
110 } else {
111 return;
112 }
113 if ( $el.length > 0 ) {
114 switchPrefTab( $el.attr( 'href' ).replace( '#mw-prefsection-', '' ) );
115 }
116 } );
117
118 // Jump to correct section as indicated by the hash.
119 // This function is called onload and onhashchange.
120 function detectHash() {
121 var hash = location.hash,
122 matchedElement, parentSection;
123 if ( hash.match( /^#mw-prefsection-[\w\-]+/ ) ) {
124 switchPrefTab( hash.replace( '#mw-prefsection-', '' ) );
125 } else if ( hash.match( /^#mw-[\w\-]+/ ) ) {
126 matchedElement = document.getElementById( hash.slice( 1 ) );
127 parentSection = $( matchedElement ).closest( '.prefsection' );
128 if ( parentSection.length ) {
129 // Switch to proper tab and scroll to selected item.
130 switchPrefTab( parentSection.attr( 'id' ).replace( 'mw-prefsection-', '' ), 'noHash' );
131 matchedElement.scrollIntoView();
132 }
133 }
134 }
135
136 // In browsers that support the onhashchange event we will not bind click
137 // handlers and instead let the browser do the default behavior (clicking the
138 // <a href="#.."> will naturally set the hash, handled by onhashchange.
139 // But other things that change the hash will also be caught (e.g. using
140 // the Back and Forward browser navigation).
141 // Note the special check for IE "compatibility" mode.
142 if ( 'onhashchange' in window &&
143 ( document.documentMode === undefined || document.documentMode >= 8 )
144 ) {
145 $( window ).on( 'hashchange', function () {
146 var hash = location.hash;
147 if ( hash.match( /^#mw-[\w\-]+/ ) ) {
148 detectHash();
149 } else if ( hash === '' ) {
150 switchPrefTab( 'personal', 'noHash' );
151 }
152 } )
153 // Run the function immediately to select the proper tab on startup.
154 .trigger( 'hashchange' );
155 // In older browsers we'll bind a click handler as fallback.
156 // We must not have onhashchange *and* the click handlers, otherwise
157 // the click handler calls switchPrefTab() which sets the hash value,
158 // which triggers onhashchange and calls switchPrefTab() again.
159 } else {
160 $preftoc.on( 'click', 'li a', function ( e ) {
161 switchPrefTab( $( this ).attr( 'href' ).replace( '#mw-prefsection-', '' ) );
162 e.preventDefault();
163 } );
164 // If we've reloaded the page or followed an open-in-new-window,
165 // make the selected tab visible.
166 detectHash();
167 }
168
169 // Timezone functions.
170 // Guesses Timezone from browser and updates fields onchange.
171
172 $tzSelect = $( '#mw-input-wptimecorrection' );
173 $tzTextbox = $( '#mw-input-wptimecorrection-other' );
174 $localtimeHolder = $( '#wpLocalTime' );
175 servertime = parseInt( $( 'input[name="wpServerTime"]' ).val(), 10 );
176
177 function minutesToHours( min ) {
178 var tzHour = Math.floor( Math.abs( min ) / 60 ),
179 tzMin = Math.abs( min ) % 60,
180 tzString = ( ( min >= 0 ) ? '' : '-' ) + ( ( tzHour < 10 ) ? '0' : '' ) + tzHour +
181 ':' + ( ( tzMin < 10 ) ? '0' : '' ) + tzMin;
182 return tzString;
183 }
184
185 function hoursToMinutes( hour ) {
186 var minutes,
187 arr = hour.split( ':' );
188
189 arr[ 0 ] = parseInt( arr[ 0 ], 10 );
190
191 if ( arr.length === 1 ) {
192 // Specification is of the form [-]XX
193 minutes = arr[ 0 ] * 60;
194 } else {
195 // Specification is of the form [-]XX:XX
196 minutes = Math.abs( arr[ 0 ] ) * 60 + parseInt( arr[ 1 ], 10 );
197 if ( arr[ 0 ] < 0 ) {
198 minutes *= -1;
199 }
200 }
201 // Gracefully handle non-numbers.
202 if ( isNaN( minutes ) ) {
203 return 0;
204 } else {
205 return minutes;
206 }
207 }
208
209 function updateTimezoneSelection() {
210 var minuteDiff, localTime,
211 type = $tzSelect.val();
212
213 if ( type === 'other' ) {
214 // User specified time zone manually in <input>
215 // Grab data from the textbox, parse it.
216 minuteDiff = hoursToMinutes( $tzTextbox.val() );
217 } else {
218 // Time zone not manually specified by user
219 if ( type === 'guess' ) {
220 // Get browser timezone & fill it in
221 minuteDiff = -( new Date().getTimezoneOffset() );
222 $tzTextbox.val( minutesToHours( minuteDiff ) );
223 $tzSelect.val( 'other' );
224 $tzTextbox.prop( 'disabled', false );
225 } else {
226 // Grab data from the $tzSelect value
227 minuteDiff = parseInt( type.split( '|' )[ 1 ], 10 ) || 0;
228 $tzTextbox.val( minutesToHours( minuteDiff ) );
229 }
230
231 // Set defaultValue prop on the generated box so we don't trigger the
232 // unsaved preferences check
233 $tzTextbox.prop( 'defaultValue', $tzTextbox.val() );
234 }
235
236 // Determine local time from server time and minutes difference, for display.
237 localTime = servertime + minuteDiff;
238
239 // Bring time within the [0,1440) range.
240 localTime = ( ( localTime % 1440 ) + 1440 ) % 1440;
241
242 $localtimeHolder.text( mw.language.convertNumber( minutesToHours( localTime ) ) );
243 }
244
245 if ( $tzSelect.length && $tzTextbox.length ) {
246 $tzSelect.change( updateTimezoneSelection );
247 $tzTextbox.blur( updateTimezoneSelection );
248 updateTimezoneSelection();
249 }
250
251 // Preserve the tab after saving the preferences
252 // Not using cookies, because their deletion results are inconsistent.
253 // Not using jStorage due to its enormous size (for this feature)
254 if ( window.sessionStorage ) {
255 if ( sessionStorage.getItem( 'mediawikiPreferencesTab' ) !== null ) {
256 switchPrefTab( sessionStorage.getItem( 'mediawikiPreferencesTab' ), 'noHash' );
257 }
258 // Deleting the key, the tab states should be reset until we press Save
259 sessionStorage.removeItem( 'mediawikiPreferencesTab' );
260
261 $( '#mw-prefs-form' ).submit( function () {
262 var storageData = $( $preftoc ).find( 'li.selected a' ).attr( 'id' ).replace( 'preftab-', '' );
263 sessionStorage.setItem( 'mediawikiPreferencesTab', storageData );
264 } );
265 }
266
267 // Check if all of the form values are unchanged
268 function isPrefsChanged() {
269 var inputs = $( '#mw-prefs-form :input[name]' ),
270 input, $input, inputType,
271 index, optIndex,
272 opt;
273
274 for ( index = 0; index < inputs.length; index++ ) {
275 input = inputs[ index ];
276 $input = $( input );
277
278 // Different types of inputs have different methods for accessing defaults
279 if ( $input.is( 'select' ) ) {
280 // <select> has the property defaultSelected for each option
281 for ( optIndex = 0; optIndex < input.options.length; optIndex++ ) {
282 opt = input.options[ optIndex ];
283 if ( opt.selected !== opt.defaultSelected ) {
284 return true;
285 }
286 }
287 } else if ( $input.is( 'input' ) ) { // <input> has defaultValue or defaultChecked
288 inputType = input.type;
289 if ( inputType === 'radio' || inputType === 'checkbox' ) {
290 if ( input.checked !== input.defaultChecked ) {
291 return true;
292 }
293 } else if ( input.value !== input.defaultValue ) {
294 return true;
295 }
296 }
297 }
298
299 return false;
300 }
301
302 // Disable the button to save preferences unless preferences have changed
303 // Check if preferences have been changed before JS has finished loading
304 if ( !isPrefsChanged() ) {
305 $( '#prefcontrol' ).prop( 'disabled', true );
306 $( '#preferences > fieldset' ).one( 'change keydown mousedown', function () {
307 $( '#prefcontrol' ).prop( 'disabled', false );
308 } );
309 }
310
311 // Set up a message to notify users if they try to leave the page without
312 // saving.
313 allowCloseWindow = mw.confirmCloseWindow( {
314 test: isPrefsChanged,
315 message: mw.msg( 'prefswarning-warning', mw.msg( 'saveprefs' ) ),
316 namespace: 'prefswarning'
317 } );
318 $( '#mw-prefs-form' ).submit( $.proxy( allowCloseWindow, 'release' ) );
319 $( '#mw-prefs-restoreprefs' ).click( $.proxy( allowCloseWindow, 'release' ) );
320 } );
321 }( mediaWiki, jQuery ) );