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