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