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