Merge "RCFilters: Don't reload the list if the change was highlights-only"
[lhc/web/wiklou.git] / resources / src / mediawiki.rcfilters / mw.rcfilters.Controller.js
1 ( function ( mw, $ ) {
2 /* eslint no-underscore-dangle: "off" */
3 /**
4 * Controller for the filters in Recent Changes
5 * @class
6 *
7 * @constructor
8 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
9 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
10 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
11 * @param {Object} config Additional configuration
12 * @cfg {string} savedQueriesPreferenceName Where to save the saved queries
13 */
14 mw.rcfilters.Controller = function MwRcfiltersController( filtersModel, changesListModel, savedQueriesModel, config ) {
15 this.filtersModel = filtersModel;
16 this.changesListModel = changesListModel;
17 this.savedQueriesModel = savedQueriesModel;
18 this.savedQueriesPreferenceName = config.savedQueriesPreferenceName;
19
20 this.requestCounter = {};
21 this.baseFilterState = {};
22 this.uriProcessor = null;
23 this.initializing = false;
24 this.wereSavedQueriesSaved = false;
25
26 this.prevLoggedItems = [];
27
28 this.FILTER_CHANGE = 'filterChange';
29 this.SHOW_NEW_CHANGES = 'showNewChanges';
30 this.LIVE_UPDATE = 'liveUpdate';
31 };
32
33 /* Initialization */
34 OO.initClass( mw.rcfilters.Controller );
35
36 /**
37 * Initialize the filter and parameter states
38 *
39 * @param {Array} filterStructure Filter definition and structure for the model
40 * @param {Object} [namespaceStructure] Namespace definition
41 * @param {Object} [tagList] Tag definition
42 */
43 mw.rcfilters.Controller.prototype.initialize = function ( filterStructure, namespaceStructure, tagList ) {
44 var parsedSavedQueries, pieces,
45 displayConfig = mw.config.get( 'StructuredChangeFiltersDisplayConfig' ),
46 defaultSavedQueryExists = mw.config.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
47 controller = this,
48 views = {},
49 items = [],
50 uri = new mw.Uri();
51
52 // Prepare views
53 if ( namespaceStructure ) {
54 items = [];
55 $.each( namespaceStructure, function ( namespaceID, label ) {
56 // Build and clean up the individual namespace items definition
57 items.push( {
58 name: namespaceID,
59 label: label || mw.msg( 'blanknamespace' ),
60 description: '',
61 identifiers: [
62 ( namespaceID < 0 || namespaceID % 2 === 0 ) ?
63 'subject' : 'talk'
64 ],
65 cssClass: 'mw-changeslist-ns-' + namespaceID
66 } );
67 } );
68
69 views.namespaces = {
70 title: mw.msg( 'namespaces' ),
71 trigger: ':',
72 groups: [ {
73 // Group definition (single group)
74 name: 'namespace', // parameter name is singular
75 type: 'string_options',
76 title: mw.msg( 'namespaces' ),
77 labelPrefixKey: { 'default': 'rcfilters-tag-prefix-namespace', inverted: 'rcfilters-tag-prefix-namespace-inverted' },
78 separator: ';',
79 fullCoverage: true,
80 filters: items
81 },
82 {
83 name: 'invertGroup',
84 type: 'boolean',
85 hidden: true,
86 filters: [ {
87 name: 'invert',
88 'default': '0'
89 } ]
90 } ]
91 };
92 }
93 if ( tagList ) {
94 views.tags = {
95 title: mw.msg( 'rcfilters-view-tags' ),
96 trigger: '#',
97 groups: [ {
98 // Group definition (single group)
99 name: 'tagfilter', // Parameter name
100 type: 'string_options',
101 title: 'rcfilters-view-tags', // Message key
102 labelPrefixKey: 'rcfilters-tag-prefix-tags',
103 separator: '|',
104 fullCoverage: false,
105 filters: tagList
106 } ]
107 };
108 }
109
110 // Add parameter range operations
111 views.range = {
112 groups: [
113 {
114 name: 'limit',
115 type: 'single_option',
116 title: '', // Because it's a hidden group, this title actually appears nowhere
117 hidden: true,
118 allowArbitrary: true,
119 validate: $.isNumeric,
120 range: {
121 min: 0, // The server normalizes negative numbers to 0 results
122 max: 1000
123 },
124 sortFunc: function ( a, b ) { return Number( a.name ) - Number( b.name ); },
125 'default': displayConfig.limitDefault,
126 // Temporarily making this not sticky until we resolve the problem
127 // with the misleading preference. Note that if this is to be permanent
128 // we should remove all sticky behavior methods completely
129 // See T172156
130 // isSticky: true,
131 excludedFromSavedQueries: true,
132 filters: displayConfig.limitArray.map( function ( num ) {
133 return controller._createFilterDataFromNumber( num, num );
134 } )
135 },
136 {
137 name: 'days',
138 type: 'single_option',
139 title: '', // Because it's a hidden group, this title actually appears nowhere
140 hidden: true,
141 allowArbitrary: true,
142 validate: $.isNumeric,
143 range: {
144 min: 0,
145 max: displayConfig.maxDays
146 },
147 sortFunc: function ( a, b ) { return Number( a.name ) - Number( b.name ); },
148 numToLabelFunc: function ( i ) {
149 return Number( i ) < 1 ?
150 ( Number( i ) * 24 ).toFixed( 2 ) :
151 Number( i );
152 },
153 'default': displayConfig.daysDefault,
154 // Temporarily making this not sticky while limit is not sticky, see above
155 // isSticky: true,
156 excludedFromSavedQueries: true,
157 filters: [
158 // Hours (1, 2, 6, 12)
159 0.04166, 0.0833, 0.25, 0.5
160 // Days
161 ].concat( displayConfig.daysArray )
162 .map( function ( num ) {
163 return controller._createFilterDataFromNumber(
164 num,
165 // Convert fractions of days to number of hours for the labels
166 num < 1 ? Math.round( num * 24 ) : num
167 );
168 } )
169 }
170 ]
171 };
172
173 views.display = {
174 groups: [
175 {
176 name: 'display',
177 type: 'boolean',
178 title: '', // Because it's a hidden group, this title actually appears nowhere
179 hidden: true,
180 isSticky: true,
181 filters: [
182 {
183 name: 'enhanced',
184 'default': String( mw.user.options.get( 'usenewrc', 0 ) )
185 }
186 ]
187 }
188 ]
189 };
190
191 // Before we do anything, we need to see if we require additional items in the
192 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
193 // groups; if we ever expand it, this might need further generalization:
194 $.each( views, function ( viewName, viewData ) {
195 viewData.groups.forEach( function ( groupData ) {
196 var extraValues = [];
197 if ( groupData.allowArbitrary ) {
198 // If the value in the URI isn't in the group, add it
199 if ( uri.query[ groupData.name ] !== undefined ) {
200 extraValues.push( uri.query[ groupData.name ] );
201 }
202 // If the default value isn't in the group, add it
203 if ( groupData.default !== undefined ) {
204 extraValues.push( String( groupData.default ) );
205 }
206 controller.addNumberValuesToGroup( groupData, extraValues );
207 }
208 } );
209 } );
210
211 // Initialize the model
212 this.filtersModel.initializeFilters( filterStructure, views );
213
214 this.uriProcessor = new mw.rcfilters.UriProcessor(
215 this.filtersModel
216 );
217
218 if ( !mw.user.isAnon() ) {
219 try {
220 parsedSavedQueries = JSON.parse( mw.user.options.get( this.savedQueriesPreferenceName ) || '{}' );
221 } catch ( err ) {
222 parsedSavedQueries = {};
223 }
224
225 // Initialize saved queries
226 this.savedQueriesModel.initialize( parsedSavedQueries );
227 if ( this.savedQueriesModel.isConverted() ) {
228 // Since we know we converted, we're going to re-save
229 // the queries so they are now migrated to the new format
230 this._saveSavedQueries();
231 }
232 }
233
234 // Check whether we need to load defaults.
235 // We do this by checking whether the current URI query
236 // contains any parameters recognized by the system.
237 // If it does, we load the given state.
238 // If it doesn't, we have no values at all, and we assume
239 // the user loads the base-page and we load defaults.
240 // Defaults should only be applied on load (if necessary)
241 // or on request
242 this.initializing = true;
243
244 if ( defaultSavedQueryExists ) {
245 // This came from the server, meaning that we have a default
246 // saved query, but the server could not load it, probably because
247 // it was pre-conversion to the new format.
248 // We need to load this query again
249 this.applySavedQuery( this.savedQueriesModel.getDefault() );
250 } else {
251 // There are either recognized parameters in the URL
252 // or there are none, but there is also no default
253 // saved query (so defaults are from the backend)
254 // We want to update the state but not fetch results
255 // again
256 this.updateStateFromUrl( false );
257
258 pieces = this._extractChangesListInfo( $( '#mw-content-text' ) );
259
260 // Update the changes list with the existing data
261 // so it gets processed
262 this.changesListModel.update(
263 pieces.changes,
264 pieces.fieldset,
265 pieces.noResultsDetails === 'NO_RESULTS_TIMEOUT',
266 true // We're using existing DOM elements
267 );
268 }
269
270 this.initializing = false;
271 this.switchView( 'default' );
272
273 this.pollingRate = mw.config.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
274 if ( this.pollingRate ) {
275 this._scheduleLiveUpdate();
276 }
277 };
278
279 /**
280 * Extracts information from the changes list DOM
281 *
282 * @param {jQuery} $root Root DOM to find children from
283 * @return {Object} Information about changes list
284 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
285 * (either normally or as an error)
286 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
287 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
288 * @return {jQuery} return.fieldset Fieldset
289 */
290 mw.rcfilters.Controller.prototype._extractChangesListInfo = function ( $root ) {
291 var info, isTimeout,
292 $changesListContents = $root.find( '.mw-changeslist' ).first().contents(),
293 areResults = !!$changesListContents.length;
294
295 info = {
296 changes: $changesListContents.length ? $changesListContents : 'NO_RESULTS',
297 fieldset: $root.find( 'fieldset.cloptions' ).first()
298 };
299
300 if ( !areResults ) {
301 isTimeout = !!$root.find( '.mw-changeslist-timeout' ).length;
302 info.noResultsDetails = isTimeout ? 'NO_RESULTS_TIMEOUT' : 'NO_RESULTS_NORMAL';
303 }
304
305 return info;
306 };
307
308 /**
309 * Create filter data from a number, for the filters that are numerical value
310 *
311 * @param {Number} num Number
312 * @param {Number} numForDisplay Number for the label
313 * @return {Object} Filter data
314 */
315 mw.rcfilters.Controller.prototype._createFilterDataFromNumber = function ( num, numForDisplay ) {
316 return {
317 name: String( num ),
318 label: mw.language.convertNumber( numForDisplay )
319 };
320 };
321
322 /**
323 * Add an arbitrary values to groups that allow arbitrary values
324 *
325 * @param {Object} groupData Group data
326 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
327 */
328 mw.rcfilters.Controller.prototype.addNumberValuesToGroup = function ( groupData, arbitraryValues ) {
329 var controller = this,
330 normalizeWithinRange = function ( range, val ) {
331 if ( val < range.min ) {
332 return range.min; // Min
333 } else if ( val >= range.max ) {
334 return range.max; // Max
335 }
336 return val;
337 };
338
339 arbitraryValues = Array.isArray( arbitraryValues ) ? arbitraryValues : [ arbitraryValues ];
340
341 // Normalize the arbitrary values and the default value for a range
342 if ( groupData.range ) {
343 arbitraryValues = arbitraryValues.map( function ( val ) {
344 return normalizeWithinRange( groupData.range, val );
345 } );
346
347 // Normalize the default, since that's user defined
348 if ( groupData.default !== undefined ) {
349 groupData.default = String( normalizeWithinRange( groupData.range, groupData.default ) );
350 }
351 }
352
353 // This is only true for single_option group
354 // We assume these are the only groups that will allow for
355 // arbitrary, since it doesn't make any sense for the other
356 // groups.
357 arbitraryValues.forEach( function ( val ) {
358 if (
359 // If the group allows for arbitrary data
360 groupData.allowArbitrary &&
361 // and it is single_option (or string_options, but we
362 // don't have cases of those yet, nor do we plan to)
363 groupData.type === 'single_option' &&
364 // and, if there is a validate method and it passes on
365 // the data
366 ( !groupData.validate || groupData.validate( val ) ) &&
367 // but if that value isn't already in the definition
368 groupData.filters
369 .map( function ( filterData ) {
370 return String( filterData.name );
371 } )
372 .indexOf( String( val ) ) === -1
373 ) {
374 // Add the filter information
375 groupData.filters.push( controller._createFilterDataFromNumber(
376 val,
377 groupData.numToLabelFunc ?
378 groupData.numToLabelFunc( val ) :
379 val
380 ) );
381
382 // If there's a sort function set up, re-sort the values
383 if ( groupData.sortFunc ) {
384 groupData.filters.sort( groupData.sortFunc );
385 }
386 }
387 } );
388 };
389
390 /**
391 * Switch the view of the filters model
392 *
393 * @param {string} view Requested view
394 */
395 mw.rcfilters.Controller.prototype.switchView = function ( view ) {
396 this.filtersModel.switchView( view );
397 };
398
399 /**
400 * Reset to default filters
401 */
402 mw.rcfilters.Controller.prototype.resetToDefaults = function () {
403 if ( this.applyParamChange( this._getDefaultParams() ) ) {
404 // Only update the changes list if there was a change to actual filters
405 this.updateChangesList();
406 }
407 };
408
409 /**
410 * Check whether the default values of the filters are all false.
411 *
412 * @return {boolean} Defaults are all false
413 */
414 mw.rcfilters.Controller.prototype.areDefaultsEmpty = function () {
415 return $.isEmptyObject( this._getDefaultParams( true ) );
416 };
417
418 /**
419 * Empty all selected filters
420 */
421 mw.rcfilters.Controller.prototype.emptyFilters = function () {
422 var highlightedFilterNames = this.filtersModel.getHighlightedItems()
423 .map( function ( filterItem ) { return { name: filterItem.getName() }; } );
424
425 if ( this.applyParamChange( {} ) ) {
426 // Only update the changes list if there was a change to actual filters
427 this.updateChangesList();
428 }
429
430 if ( highlightedFilterNames ) {
431 this._trackHighlight( 'clearAll', highlightedFilterNames );
432 }
433 };
434
435 /**
436 * Update the selected state of a filter
437 *
438 * @param {string} filterName Filter name
439 * @param {boolean} [isSelected] Filter selected state
440 */
441 mw.rcfilters.Controller.prototype.toggleFilterSelect = function ( filterName, isSelected ) {
442 var filterItem = this.filtersModel.getItemByName( filterName );
443
444 if ( !filterItem ) {
445 // If no filter was found, break
446 return;
447 }
448
449 isSelected = isSelected === undefined ? !filterItem.isSelected() : isSelected;
450
451 if ( filterItem.isSelected() !== isSelected ) {
452 this.filtersModel.toggleFilterSelected( filterName, isSelected );
453
454 this.updateChangesList();
455
456 // Check filter interactions
457 this.filtersModel.reassessFilterInteractions( filterItem );
458 }
459 };
460
461 /**
462 * Clear both highlight and selection of a filter
463 *
464 * @param {string} filterName Name of the filter item
465 */
466 mw.rcfilters.Controller.prototype.clearFilter = function ( filterName ) {
467 var filterItem = this.filtersModel.getItemByName( filterName ),
468 isHighlighted = filterItem.isHighlighted(),
469 isSelected = filterItem.isSelected();
470
471 if ( isSelected || isHighlighted ) {
472 this.filtersModel.clearHighlightColor( filterName );
473 this.filtersModel.toggleFilterSelected( filterName, false );
474
475 if ( isSelected ) {
476 // Only update the changes list if the filter changed
477 // its selection state. If it only changed its highlight
478 // then don't reload
479 this.updateChangesList();
480 }
481
482 this.filtersModel.reassessFilterInteractions( filterItem );
483
484 // Log filter grouping
485 this.trackFilterGroupings( 'removefilter' );
486 }
487
488 if ( isHighlighted ) {
489 this._trackHighlight( 'clear', filterName );
490 }
491 };
492
493 /**
494 * Toggle the highlight feature on and off
495 */
496 mw.rcfilters.Controller.prototype.toggleHighlight = function () {
497 this.filtersModel.toggleHighlight();
498 this.uriProcessor.updateURL();
499
500 if ( this.filtersModel.isHighlightEnabled() ) {
501 mw.hook( 'RcFilters.highlight.enable' ).fire();
502 }
503 };
504
505 /**
506 * Toggle the namespaces inverted feature on and off
507 */
508 mw.rcfilters.Controller.prototype.toggleInvertedNamespaces = function () {
509 this.filtersModel.toggleInvertedNamespaces();
510
511 if (
512 this.filtersModel.getFiltersByView( 'namespaces' ).filter(
513 function ( filterItem ) { return filterItem.isSelected(); }
514 ).length
515 ) {
516 // Only re-fetch results if there are namespace items that are actually selected
517 this.updateChangesList();
518 }
519 };
520
521 /**
522 * Set the highlight color for a filter item
523 *
524 * @param {string} filterName Name of the filter item
525 * @param {string} color Selected color
526 */
527 mw.rcfilters.Controller.prototype.setHighlightColor = function ( filterName, color ) {
528 this.filtersModel.setHighlightColor( filterName, color );
529 this.uriProcessor.updateURL();
530 this._trackHighlight( 'set', { name: filterName, color: color } );
531 };
532
533 /**
534 * Clear highlight for a filter item
535 *
536 * @param {string} filterName Name of the filter item
537 */
538 mw.rcfilters.Controller.prototype.clearHighlightColor = function ( filterName ) {
539 this.filtersModel.clearHighlightColor( filterName );
540 this.uriProcessor.updateURL();
541 this._trackHighlight( 'clear', filterName );
542 };
543
544 /**
545 * Enable or disable live updates.
546 * @param {boolean} enable True to enable, false to disable
547 */
548 mw.rcfilters.Controller.prototype.toggleLiveUpdate = function ( enable ) {
549 this.changesListModel.toggleLiveUpdate( enable );
550 if ( this.changesListModel.getLiveUpdate() && this.changesListModel.getNewChangesExist() ) {
551 this.updateChangesList( null, this.LIVE_UPDATE );
552 }
553 };
554
555 /**
556 * Set a timeout for the next live update.
557 * @private
558 */
559 mw.rcfilters.Controller.prototype._scheduleLiveUpdate = function () {
560 setTimeout( this._doLiveUpdate.bind( this ), this.pollingRate * 1000 );
561 };
562
563 /**
564 * Perform a live update.
565 * @private
566 */
567 mw.rcfilters.Controller.prototype._doLiveUpdate = function () {
568 if ( !this._shouldCheckForNewChanges() ) {
569 // skip this turn and check back later
570 this._scheduleLiveUpdate();
571 return;
572 }
573
574 this._checkForNewChanges()
575 .then( function ( newChanges ) {
576 if ( !this._shouldCheckForNewChanges() ) {
577 // by the time the response is received,
578 // it may not be appropriate anymore
579 return;
580 }
581
582 if ( newChanges ) {
583 if ( this.changesListModel.getLiveUpdate() ) {
584 return this.updateChangesList( null, this.LIVE_UPDATE );
585 } else {
586 this.changesListModel.setNewChangesExist( true );
587 }
588 }
589 }.bind( this ) )
590 .always( this._scheduleLiveUpdate.bind( this ) );
591 };
592
593 /**
594 * @return {boolean} It's appropriate to check for new changes now
595 * @private
596 */
597 mw.rcfilters.Controller.prototype._shouldCheckForNewChanges = function () {
598 return !document.hidden &&
599 !this.filtersModel.hasConflict() &&
600 !this.changesListModel.getNewChangesExist() &&
601 !this.updatingChangesList &&
602 this.changesListModel.getNextFrom();
603 };
604
605 /**
606 * Check if new changes, newer than those currently shown, are available
607 *
608 * @return {jQuery.Promise} Promise object that resolves with a bool
609 * specifying if there are new changes or not
610 *
611 * @private
612 */
613 mw.rcfilters.Controller.prototype._checkForNewChanges = function () {
614 var params = {
615 limit: 1,
616 peek: 1, // bypasses ChangesList specific UI
617 from: this.changesListModel.getNextFrom()
618 };
619 return this._queryChangesList( 'liveUpdate', params ).then(
620 function ( data ) {
621 // no result is 204 with the 'peek' param
622 return data.status === 200;
623 }
624 );
625 };
626
627 /**
628 * Show the new changes
629 *
630 * @return {jQuery.Promise} Promise object that resolves after
631 * fetching and showing the new changes
632 */
633 mw.rcfilters.Controller.prototype.showNewChanges = function () {
634 return this.updateChangesList( null, this.SHOW_NEW_CHANGES );
635 };
636
637 /**
638 * Save the current model state as a saved query
639 *
640 * @param {string} [label] Label of the saved query
641 * @param {boolean} [setAsDefault=false] This query should be set as the default
642 */
643 mw.rcfilters.Controller.prototype.saveCurrentQuery = function ( label, setAsDefault ) {
644 // Add item
645 this.savedQueriesModel.addNewQuery(
646 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
647 this.filtersModel.getCurrentParameterState( true ),
648 setAsDefault
649 );
650
651 // Save item
652 this._saveSavedQueries();
653 };
654
655 /**
656 * Remove a saved query
657 *
658 * @param {string} queryID Query id
659 */
660 mw.rcfilters.Controller.prototype.removeSavedQuery = function ( queryID ) {
661 this.savedQueriesModel.removeQuery( queryID );
662
663 this._saveSavedQueries();
664 };
665
666 /**
667 * Rename a saved query
668 *
669 * @param {string} queryID Query id
670 * @param {string} newLabel New label for the query
671 */
672 mw.rcfilters.Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
673 var queryItem = this.savedQueriesModel.getItemByID( queryID );
674
675 if ( queryItem ) {
676 queryItem.updateLabel( newLabel );
677 }
678 this._saveSavedQueries();
679 };
680
681 /**
682 * Set a saved query as default
683 *
684 * @param {string} queryID Query Id. If null is given, default
685 * query is reset.
686 */
687 mw.rcfilters.Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
688 this.savedQueriesModel.setDefault( queryID );
689 this._saveSavedQueries();
690 };
691
692 /**
693 * Load a saved query
694 *
695 * @param {string} queryID Query id
696 */
697 mw.rcfilters.Controller.prototype.applySavedQuery = function ( queryID ) {
698 var currentMatchingQuery,
699 params = this.savedQueriesModel.getItemParams( queryID );
700
701 currentMatchingQuery = this.findQueryMatchingCurrentState();
702
703 if (
704 currentMatchingQuery &&
705 currentMatchingQuery.getID() === queryID
706 ) {
707 // If the query we want to load is the one that is already
708 // loaded, don't reload it
709 return;
710 }
711
712 if ( this.applyParamChange( params ) ) {
713 // Update changes list only if there was a difference in filter selection
714 this.updateChangesList();
715 }
716
717 // Log filter grouping
718 this.trackFilterGroupings( 'savedfilters' );
719 };
720
721 /**
722 * Check whether the current filter and highlight state exists
723 * in the saved queries model.
724 *
725 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
726 */
727 mw.rcfilters.Controller.prototype.findQueryMatchingCurrentState = function () {
728 return this.savedQueriesModel.findMatchingQuery(
729 this.filtersModel.getCurrentParameterState( true )
730 );
731 };
732
733 /**
734 * Save the current state of the saved queries model with all
735 * query item representation in the user settings.
736 */
737 mw.rcfilters.Controller.prototype._saveSavedQueries = function () {
738 var stringified, oldPrefValue,
739 backupPrefName = this.savedQueriesPreferenceName + '-versionbackup',
740 state = this.savedQueriesModel.getState();
741
742 // Stringify state
743 stringified = JSON.stringify( state );
744
745 if ( $.byteLength( stringified ) > 65535 ) {
746 // Sanity check, since the preference can only hold that.
747 return;
748 }
749
750 if ( !this.wereSavedQueriesSaved && this.savedQueriesModel.isConverted() ) {
751 // The queries were converted from the previous version
752 // Keep the old string in the [prefname]-versionbackup
753 oldPrefValue = mw.user.options.get( this.savedQueriesPreferenceName );
754
755 // Save the old preference in the backup preference
756 new mw.Api().saveOption( backupPrefName, oldPrefValue );
757 // Update the preference for this session
758 mw.user.options.set( backupPrefName, oldPrefValue );
759 }
760
761 // Save the preference
762 new mw.Api().saveOption( this.savedQueriesPreferenceName, stringified );
763 // Update the preference for this session
764 mw.user.options.set( this.savedQueriesPreferenceName, stringified );
765
766 // Tag as already saved so we don't do this again
767 this.wereSavedQueriesSaved = true;
768 };
769
770 /**
771 * Update sticky preferences with current model state
772 */
773 mw.rcfilters.Controller.prototype.updateStickyPreferences = function () {
774 // Update default sticky values with selected, whether they came from
775 // the initial defaults or from the URL value that is being normalized
776 this.updateDaysDefault( this.filtersModel.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
777 this.updateLimitDefault( this.filtersModel.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
778
779 // TODO: Make these automatic by having the model go over sticky
780 // items and update their default values automatically
781 };
782
783 /**
784 * Update the limit default value
785 *
786 * param {number} newValue New value
787 */
788 mw.rcfilters.Controller.prototype.updateLimitDefault = function ( /* newValue */ ) {
789 // HACK: Temporarily remove this from being sticky
790 // See T172156
791
792 /*
793 if ( !$.isNumeric( newValue ) ) {
794 return;
795 }
796
797 newValue = Number( newValue );
798
799 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
800 // Save the preference
801 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
802 // Update the preference for this session
803 mw.user.options.set( 'rcfilters-rclimit', newValue );
804 }
805 */
806 return;
807 };
808
809 /**
810 * Update the days default value
811 *
812 * param {number} newValue New value
813 */
814 mw.rcfilters.Controller.prototype.updateDaysDefault = function ( /* newValue */ ) {
815 // HACK: Temporarily remove this from being sticky
816 // See T172156
817
818 /*
819 if ( !$.isNumeric( newValue ) ) {
820 return;
821 }
822
823 newValue = Number( newValue );
824
825 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
826 // Save the preference
827 new mw.Api().saveOption( 'rcdays', newValue );
828 // Update the preference for this session
829 mw.user.options.set( 'rcdays', newValue );
830 }
831 */
832 return;
833 };
834
835 /**
836 * Update the group by page default value
837 *
838 * @param {number} newValue New value
839 */
840 mw.rcfilters.Controller.prototype.updateGroupByPageDefault = function ( newValue ) {
841 if ( !$.isNumeric( newValue ) ) {
842 return;
843 }
844
845 newValue = Number( newValue );
846
847 if ( mw.user.options.get( 'usenewrc' ) !== newValue ) {
848 // Save the preference
849 new mw.Api().saveOption( 'usenewrc', newValue );
850 // Update the preference for this session
851 mw.user.options.set( 'usenewrc', newValue );
852 }
853 };
854
855 /**
856 * Synchronize the URL with the current state of the filters
857 * without adding an history entry.
858 */
859 mw.rcfilters.Controller.prototype.replaceUrl = function () {
860 this.uriProcessor.updateURL();
861 };
862
863 /**
864 * Update filter state (selection and highlighting) based
865 * on current URL values.
866 *
867 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
868 * list based on the updated model.
869 */
870 mw.rcfilters.Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
871 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
872
873 this.uriProcessor.updateModelBasedOnQuery( new mw.Uri().query );
874
875 // Update the sticky preferences, in case we received a value
876 // from the URL
877 this.updateStickyPreferences();
878
879 // Only update and fetch new results if it is requested
880 if ( fetchChangesList ) {
881 this.updateChangesList();
882 }
883 };
884
885 /**
886 * Update the list of changes and notify the model
887 *
888 * @param {Object} [params] Extra parameters to add to the API call
889 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
890 * @return {jQuery.Promise} Promise that is resolved when the update is complete
891 */
892 mw.rcfilters.Controller.prototype.updateChangesList = function ( params, updateMode ) {
893 updateMode = updateMode === undefined ? this.FILTER_CHANGE : updateMode;
894
895 if ( updateMode === this.FILTER_CHANGE ) {
896 this.uriProcessor.updateURL( params );
897 }
898 if ( updateMode === this.FILTER_CHANGE || updateMode === this.SHOW_NEW_CHANGES ) {
899 this.changesListModel.invalidate();
900 }
901 this.changesListModel.setNewChangesExist( false );
902 this.updatingChangesList = true;
903 return this._fetchChangesList()
904 .then(
905 // Success
906 function ( pieces ) {
907 var $changesListContent = pieces.changes,
908 $fieldset = pieces.fieldset;
909 this.changesListModel.update(
910 $changesListContent,
911 $fieldset,
912 pieces.noResultsDetails,
913 false,
914 // separator between old and new changes
915 updateMode === this.SHOW_NEW_CHANGES || updateMode === this.LIVE_UPDATE
916 );
917 }.bind( this )
918 // Do nothing for failure
919 )
920 .always( function () {
921 this.updatingChangesList = false;
922 }.bind( this ) );
923 };
924
925 /**
926 * Get an object representing the default parameter state, whether
927 * it is from the model defaults or from the saved queries.
928 *
929 * @param {boolean} [excludeHiddenParams] Exclude hidden and sticky params
930 * @return {Object} Default parameters
931 */
932 mw.rcfilters.Controller.prototype._getDefaultParams = function ( excludeHiddenParams ) {
933 if ( this.savedQueriesModel.getDefault() ) {
934 return this.savedQueriesModel.getDefaultParams( excludeHiddenParams );
935 } else {
936 return this.filtersModel.getDefaultParams( excludeHiddenParams );
937 }
938 };
939
940 /**
941 * Query the list of changes from the server for the current filters
942 *
943 * @param {string} counterId Id for this request. To allow concurrent requests
944 * not to invalidate each other.
945 * @param {Object} [params={}] Parameters to add to the query
946 *
947 * @return {jQuery.Promise} Promise object resolved with { content, status }
948 */
949 mw.rcfilters.Controller.prototype._queryChangesList = function ( counterId, params ) {
950 var uri = this.uriProcessor.getUpdatedUri(),
951 stickyParams = this.filtersModel.getStickyParamsValues(),
952 requestId,
953 latestRequest;
954
955 params = params || {};
956 params.action = 'render'; // bypasses MW chrome
957
958 uri.extend( params );
959
960 this.requestCounter[ counterId ] = this.requestCounter[ counterId ] || 0;
961 requestId = ++this.requestCounter[ counterId ];
962 latestRequest = function () {
963 return requestId === this.requestCounter[ counterId ];
964 }.bind( this );
965
966 // Sticky parameters override the URL params
967 // this is to make sure that whether we represent
968 // the sticky params in the URL or not (they may
969 // be normalized out) the sticky parameters are
970 // always being sent to the server with their
971 // current/default values
972 uri.extend( stickyParams );
973
974 return $.ajax( uri.toString(), { contentType: 'html' } )
975 .then(
976 function ( content, message, jqXHR ) {
977 if ( !latestRequest() ) {
978 return $.Deferred().reject();
979 }
980 return {
981 content: content,
982 status: jqXHR.status
983 };
984 },
985 // RC returns 404 when there is no results
986 function ( jqXHR ) {
987 if ( latestRequest() ) {
988 return $.Deferred().resolve(
989 {
990 content: jqXHR.responseText,
991 status: jqXHR.status
992 }
993 ).promise();
994 }
995 }
996 );
997 };
998
999 /**
1000 * Fetch the list of changes from the server for the current filters
1001 *
1002 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1003 * and the fieldset.
1004 */
1005 mw.rcfilters.Controller.prototype._fetchChangesList = function () {
1006 return this._queryChangesList( 'updateChangesList' )
1007 .then(
1008 function ( data ) {
1009 var $parsed;
1010
1011 // Status code 0 is not HTTP status code,
1012 // but is valid value of XMLHttpRequest status.
1013 // It is used for variety of network errors, for example
1014 // when an AJAX call was cancelled before getting the response
1015 if ( data && data.status === 0 ) {
1016 return {
1017 changes: 'NO_RESULTS',
1018 // We need empty result set, to avoid exceptions because of undefined value
1019 fieldset: $( [] ),
1020 noResultsDetails: 'NO_RESULTS_NETWORK_ERROR'
1021 };
1022 }
1023
1024 $parsed = $( '<div>' ).append( $( $.parseHTML( data.content ) ) );
1025
1026 return this._extractChangesListInfo( $parsed );
1027
1028 }.bind( this )
1029 );
1030 };
1031
1032 /**
1033 * Track usage of highlight feature
1034 *
1035 * @param {string} action
1036 * @param {Array|Object|string} filters
1037 */
1038 mw.rcfilters.Controller.prototype._trackHighlight = function ( action, filters ) {
1039 filters = typeof filters === 'string' ? { name: filters } : filters;
1040 filters = !Array.isArray( filters ) ? [ filters ] : filters;
1041 mw.track(
1042 'event.ChangesListHighlights',
1043 {
1044 action: action,
1045 filters: filters,
1046 userId: mw.user.getId()
1047 }
1048 );
1049 };
1050
1051 /**
1052 * Track filter grouping usage
1053 *
1054 * @param {string} action Action taken
1055 */
1056 mw.rcfilters.Controller.prototype.trackFilterGroupings = function ( action ) {
1057 var controller = this,
1058 rightNow = new Date().getTime(),
1059 randomIdentifier = String( mw.user.sessionId() ) + String( rightNow ) + String( Math.random() ),
1060 // Get all current filters
1061 filters = this.filtersModel.getSelectedItems().map( function ( item ) {
1062 return item.getName();
1063 } );
1064
1065 action = action || 'filtermenu';
1066
1067 // Check if these filters were the ones we just logged previously
1068 // (Don't log the same grouping twice, in case the user opens/closes)
1069 // the menu without action, or with the same result
1070 if (
1071 // Only log if the two arrays are different in size
1072 filters.length !== this.prevLoggedItems.length ||
1073 // Or if any filters are not the same as the cached filters
1074 filters.some( function ( filterName ) {
1075 return controller.prevLoggedItems.indexOf( filterName ) === -1;
1076 } ) ||
1077 // Or if any cached filters are not the same as given filters
1078 this.prevLoggedItems.some( function ( filterName ) {
1079 return filters.indexOf( filterName ) === -1;
1080 } )
1081 ) {
1082 filters.forEach( function ( filterName ) {
1083 mw.track(
1084 'event.ChangesListFilterGrouping',
1085 {
1086 action: action,
1087 groupIdentifier: randomIdentifier,
1088 filter: filterName,
1089 userId: mw.user.getId()
1090 }
1091 );
1092 } );
1093
1094 // Cache the filter names
1095 this.prevLoggedItems = filters;
1096 }
1097 };
1098
1099 /**
1100 * Apply a change of parameters to the model state, and check whether
1101 * the new state is different than the old state.
1102 *
1103 * @param {Object} newParamState New parameter state to apply
1104 * @return {boolean} New applied model state is different than the previous state
1105 */
1106 mw.rcfilters.Controller.prototype.applyParamChange = function ( newParamState ) {
1107 var after,
1108 before = this.filtersModel.getSelectedState();
1109
1110 this.filtersModel.updateStateFromParams( newParamState );
1111
1112 after = this.filtersModel.getSelectedState();
1113
1114 return !OO.compare( before, after );
1115 };
1116
1117 /**
1118 * Mark all changes as seen on Watchlist
1119 */
1120 mw.rcfilters.Controller.prototype.markAllChangesAsSeen = function () {
1121 var api = new mw.Api();
1122 api.postWithToken( 'csrf', {
1123 formatversion: 2,
1124 action: 'setnotificationtimestamp',
1125 entirewatchlist: true
1126 } ).then( function () {
1127 this.updateChangesList( null, 'markSeen' );
1128 }.bind( this ) );
1129 };
1130 }( mediaWiki, jQuery ) );