f90f85914f39b6ab952d098773b940cb32e25df5
[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 // Remove now-unnecessary success=1 querystring to prevent reappearance of notification on reload
99 if ( history.replaceState ) {
100 history.replaceState( {}, document.title, location.href.replace( /&?success=1/, '' ) );
101 }
102 }
103 }
104
105 // Enable keyboard users to use left and right keys to switch tabs
106 $preftoc.on( 'keydown', function ( event ) {
107 var keyLeft = 37,
108 keyRight = 39,
109 $el;
110
111 if ( event.keyCode === keyLeft ) {
112 $el = $( '#preftoc li.selected' ).prev().find( 'a' );
113 } else if ( event.keyCode === keyRight ) {
114 $el = $( '#preftoc li.selected' ).next().find( 'a' );
115 } else {
116 return;
117 }
118 if ( $el.length > 0 ) {
119 switchPrefTab( $el.attr( 'href' ).replace( '#mw-prefsection-', '' ) );
120 }
121 } );
122
123 // Jump to correct section as indicated by the hash.
124 // This function is called onload and onhashchange.
125 function detectHash() {
126 var hash = location.hash,
127 matchedElement, parentSection;
128 if ( hash.match( /^#mw-prefsection-[\w\-]+/ ) ) {
129 switchPrefTab( hash.replace( '#mw-prefsection-', '' ) );
130 } else if ( hash.match( /^#mw-[\w\-]+/ ) ) {
131 matchedElement = document.getElementById( hash.slice( 1 ) );
132 parentSection = $( matchedElement ).closest( '.prefsection' );
133 if ( parentSection.length ) {
134 // Switch to proper tab and scroll to selected item.
135 switchPrefTab( parentSection.attr( 'id' ).replace( 'mw-prefsection-', '' ), 'noHash' );
136 matchedElement.scrollIntoView();
137 }
138 }
139 }
140
141 // In browsers that support the onhashchange event we will not bind click
142 // handlers and instead let the browser do the default behavior (clicking the
143 // <a href="#.."> will naturally set the hash, handled by onhashchange.
144 // But other things that change the hash will also be caught (e.g. using
145 // the Back and Forward browser navigation).
146 // Note the special check for IE "compatibility" mode.
147 if ( 'onhashchange' in window &&
148 ( document.documentMode === undefined || document.documentMode >= 8 )
149 ) {
150 $( window ).on( 'hashchange', function () {
151 var hash = location.hash;
152 if ( hash.match( /^#mw-[\w\-]+/ ) ) {
153 detectHash();
154 } else if ( hash === '' ) {
155 switchPrefTab( 'personal', 'noHash' );
156 }
157 } )
158 // Run the function immediately to select the proper tab on startup.
159 .trigger( 'hashchange' );
160 // In older browsers we'll bind a click handler as fallback.
161 // We must not have onhashchange *and* the click handlers, otherwise
162 // the click handler calls switchPrefTab() which sets the hash value,
163 // which triggers onhashchange and calls switchPrefTab() again.
164 } else {
165 $preftoc.on( 'click', 'li a', function ( e ) {
166 switchPrefTab( $( this ).attr( 'href' ).replace( '#mw-prefsection-', '' ) );
167 e.preventDefault();
168 } );
169 // If we've reloaded the page or followed an open-in-new-window,
170 // make the selected tab visible.
171 detectHash();
172 }
173
174 // Timezone functions.
175 // Guesses Timezone from browser and updates fields onchange.
176
177 $tzSelect = $( '#mw-input-wptimecorrection' );
178 $tzTextbox = $( '#mw-input-wptimecorrection-other' );
179 $localtimeHolder = $( '#wpLocalTime' );
180 servertime = parseInt( $( 'input[name="wpServerTime"]' ).val(), 10 );
181
182 function minutesToHours( min ) {
183 var tzHour = Math.floor( Math.abs( min ) / 60 ),
184 tzMin = Math.abs( min ) % 60,
185 tzString = ( ( min >= 0 ) ? '' : '-' ) + ( ( tzHour < 10 ) ? '0' : '' ) + tzHour +
186 ':' + ( ( tzMin < 10 ) ? '0' : '' ) + tzMin;
187 return tzString;
188 }
189
190 function hoursToMinutes( hour ) {
191 var minutes,
192 arr = hour.split( ':' );
193
194 arr[ 0 ] = parseInt( arr[ 0 ], 10 );
195
196 if ( arr.length === 1 ) {
197 // Specification is of the form [-]XX
198 minutes = arr[ 0 ] * 60;
199 } else {
200 // Specification is of the form [-]XX:XX
201 minutes = Math.abs( arr[ 0 ] ) * 60 + parseInt( arr[ 1 ], 10 );
202 if ( arr[ 0 ] < 0 ) {
203 minutes *= -1;
204 }
205 }
206 // Gracefully handle non-numbers.
207 if ( isNaN( minutes ) ) {
208 return 0;
209 } else {
210 return minutes;
211 }
212 }
213
214 function updateTimezoneSelection() {
215 var minuteDiff, localTime,
216 type = $tzSelect.val();
217
218 if ( type === 'guess' ) {
219 // Get browser timezone & fill it in
220 minuteDiff = -( new Date().getTimezoneOffset() );
221 $tzTextbox.val( minutesToHours( minuteDiff ) );
222 $tzSelect.val( 'other' );
223 $tzTextbox.prop( 'disabled', false );
224 } else if ( type === 'other' ) {
225 // Grab data from the textbox, parse it.
226 minuteDiff = hoursToMinutes( $tzTextbox.val() );
227 } else {
228 // Grab data from the $tzSelect value
229 minuteDiff = parseInt( type.split( '|' )[ 1 ], 10 ) || 0;
230 $tzTextbox.val( minutesToHours( minuteDiff ) );
231 }
232
233 // Determine local time from server time and minutes difference, for display.
234 localTime = servertime + minuteDiff;
235
236 // Bring time within the [0,1440) range.
237 localTime = ( ( localTime % 1440 ) + 1440 ) % 1440;
238
239 $localtimeHolder.text( mw.language.convertNumber( minutesToHours( localTime ) ) );
240 }
241
242 if ( $tzSelect.length && $tzTextbox.length ) {
243 $tzSelect.change( updateTimezoneSelection );
244 $tzTextbox.blur( updateTimezoneSelection );
245 updateTimezoneSelection();
246 }
247
248 // Preserve the tab after saving the preferences
249 // Not using cookies, because their deletion results are inconsistent.
250 // Not using jStorage due to its enormous size (for this feature)
251 if ( window.sessionStorage ) {
252 if ( sessionStorage.getItem( 'mediawikiPreferencesTab' ) !== null ) {
253 switchPrefTab( sessionStorage.getItem( 'mediawikiPreferencesTab' ), 'noHash' );
254 }
255 // Deleting the key, the tab states should be reset until we press Save
256 sessionStorage.removeItem( 'mediawikiPreferencesTab' );
257
258 $( '#mw-prefs-form' ).submit( function () {
259 var storageData = $( $preftoc ).find( 'li.selected a' ).attr( 'id' ).replace( 'preftab-', '' );
260 sessionStorage.setItem( 'mediawikiPreferencesTab', storageData );
261 } );
262 }
263
264 // Set up a message to notify users if they try to leave the page without
265 // saving.
266 $( '#mw-prefs-form' ).data( 'origdata', $( '#mw-prefs-form' ).serialize() );
267 allowCloseWindow = mw.confirmCloseWindow( {
268 test: function () {
269 return $( '#mw-prefs-form' ).serialize() !== $( '#mw-prefs-form' ).data( 'origdata' );
270 },
271
272 message: mw.msg( 'prefswarning-warning', mw.msg( 'saveprefs' ) ),
273 namespace: 'prefswarning'
274 } );
275 $( '#mw-prefs-form' ).submit( $.proxy( allowCloseWindow, 'release' ) );
276 $( '#mw-prefs-restoreprefs' ).click( $.proxy( allowCloseWindow, 'release' ) );
277 } );
278 }( mediaWiki, jQuery ) );