2 /* eslint no-underscore-dangle: "off" */
4 * Controller for the filters in Recent Changes
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 * @cfg {string} daysPreferenceName Preference name for the days filter
14 * @cfg {string} limitPreferenceName Preference name for the limit filter
16 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
, config
) {
17 this.filtersModel
= filtersModel
;
18 this.changesListModel
= changesListModel
;
19 this.savedQueriesModel
= savedQueriesModel
;
20 this.savedQueriesPreferenceName
= config
.savedQueriesPreferenceName
;
21 this.daysPreferenceName
= config
.daysPreferenceName
;
22 this.limitPreferenceName
= config
.limitPreferenceName
;
24 this.requestCounter
= {};
25 this.baseFilterState
= {};
26 this.uriProcessor
= null;
27 this.initializing
= false;
28 this.wereSavedQueriesSaved
= false;
30 this.prevLoggedItems
= [];
32 this.FILTER_CHANGE
= 'filterChange';
33 this.SHOW_NEW_CHANGES
= 'showNewChanges';
34 this.LIVE_UPDATE
= 'liveUpdate';
38 OO
.initClass( mw
.rcfilters
.Controller
);
41 * Initialize the filter and parameter states
43 * @param {Array} filterStructure Filter definition and structure for the model
44 * @param {Object} [namespaceStructure] Namespace definition
45 * @param {Object} [tagList] Tag definition
47 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
48 var parsedSavedQueries
, pieces
,
49 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
50 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
57 if ( namespaceStructure
) {
59 $.each( namespaceStructure
, function ( namespaceID
, label
) {
60 // Build and clean up the individual namespace items definition
63 label
: label
|| mw
.msg( 'blanknamespace' ),
66 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
69 cssClass
: 'mw-changeslist-ns-' + namespaceID
74 title
: mw
.msg( 'namespaces' ),
77 // Group definition (single group)
78 name
: 'namespace', // parameter name is singular
79 type
: 'string_options',
80 title
: mw
.msg( 'namespaces' ),
81 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
99 title
: mw
.msg( 'rcfilters-view-tags' ),
102 // Group definition (single group)
103 name
: 'tagfilter', // Parameter name
104 type
: 'string_options',
105 title
: 'rcfilters-view-tags', // Message key
106 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
114 // Add parameter range operations
119 type
: 'single_option',
120 title
: '', // Because it's a hidden group, this title actually appears nowhere
122 allowArbitrary
: true,
123 validate
: $.isNumeric
,
125 min
: 0, // The server normalizes negative numbers to 0 results
128 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
129 'default': mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
131 excludedFromSavedQueries
: true,
132 filters
: displayConfig
.limitArray
.map( function ( num
) {
133 return controller
._createFilterDataFromNumber( num
, num
);
138 type
: 'single_option',
139 title
: '', // Because it's a hidden group, this title actually appears nowhere
141 allowArbitrary
: true,
142 validate
: $.isNumeric
,
145 max
: displayConfig
.maxDays
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 ) :
153 'default': mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
155 excludedFromSavedQueries
: true,
157 // Hours (1, 2, 6, 12)
158 0.04166, 0.0833, 0.25, 0.5
160 ].concat( displayConfig
.daysArray
)
161 .map( function ( num
) {
162 return controller
._createFilterDataFromNumber(
164 // Convert fractions of days to number of hours for the labels
165 num
< 1 ? Math
.round( num
* 24 ) : num
177 title
: '', // Because it's a hidden group, this title actually appears nowhere
183 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
190 // Before we do anything, we need to see if we require additional items in the
191 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
192 // groups; if we ever expand it, this might need further generalization:
193 $.each( views
, function ( viewName
, viewData
) {
194 viewData
.groups
.forEach( function ( groupData
) {
195 var extraValues
= [];
196 if ( groupData
.allowArbitrary
) {
197 // If the value in the URI isn't in the group, add it
198 if ( uri
.query
[ groupData
.name
] !== undefined ) {
199 extraValues
.push( uri
.query
[ groupData
.name
] );
201 // If the default value isn't in the group, add it
202 if ( groupData
.default !== undefined ) {
203 extraValues
.push( String( groupData
.default ) );
205 controller
.addNumberValuesToGroup( groupData
, extraValues
);
210 // Initialize the model
211 this.filtersModel
.initializeFilters( filterStructure
, views
);
213 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
217 if ( !mw
.user
.isAnon() ) {
219 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
221 parsedSavedQueries
= {};
224 // Initialize saved queries
225 this.savedQueriesModel
.initialize( parsedSavedQueries
);
226 if ( this.savedQueriesModel
.isConverted() ) {
227 // Since we know we converted, we're going to re-save
228 // the queries so they are now migrated to the new format
229 this._saveSavedQueries();
233 // Check whether we need to load defaults.
234 // We do this by checking whether the current URI query
235 // contains any parameters recognized by the system.
236 // If it does, we load the given state.
237 // If it doesn't, we have no values at all, and we assume
238 // the user loads the base-page and we load defaults.
239 // Defaults should only be applied on load (if necessary)
241 this.initializing
= true;
243 if ( defaultSavedQueryExists
) {
244 // This came from the server, meaning that we have a default
245 // saved query, but the server could not load it, probably because
246 // it was pre-conversion to the new format.
247 // We need to load this query again
248 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
250 // There are either recognized parameters in the URL
251 // or there are none, but there is also no default
252 // saved query (so defaults are from the backend)
253 // We want to update the state but not fetch results
255 this.updateStateFromUrl( false );
257 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
259 // Update the changes list with the existing data
260 // so it gets processed
261 this.changesListModel
.update(
264 pieces
.noResultsDetails
,
265 true // We're using existing DOM elements
269 this.initializing
= false;
270 this.switchView( 'default' );
272 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
273 if ( this.pollingRate
) {
274 this._scheduleLiveUpdate();
279 * Extracts information from the changes list DOM
281 * @param {jQuery} $root Root DOM to find children from
282 * @return {Object} Information about changes list
283 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
284 * (either normally or as an error)
285 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
286 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
287 * @return {jQuery} return.fieldset Fieldset
289 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
) {
291 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
292 areResults
= !!$changesListContents
.length
;
295 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
296 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
300 isTimeout
= !!$root
.find( '.mw-changeslist-timeout' ).length
;
301 info
.noResultsDetails
= isTimeout
? 'NO_RESULTS_TIMEOUT' : 'NO_RESULTS_NORMAL';
308 * Create filter data from a number, for the filters that are numerical value
310 * @param {Number} num Number
311 * @param {Number} numForDisplay Number for the label
312 * @return {Object} Filter data
314 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
317 label
: mw
.language
.convertNumber( numForDisplay
)
322 * Add an arbitrary values to groups that allow arbitrary values
324 * @param {Object} groupData Group data
325 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
327 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
328 var controller
= this,
329 normalizeWithinRange = function ( range
, val
) {
330 if ( val
< range
.min
) {
331 return range
.min
; // Min
332 } else if ( val
>= range
.max
) {
333 return range
.max
; // Max
338 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
340 // Normalize the arbitrary values and the default value for a range
341 if ( groupData
.range
) {
342 arbitraryValues
= arbitraryValues
.map( function ( val
) {
343 return normalizeWithinRange( groupData
.range
, val
);
346 // Normalize the default, since that's user defined
347 if ( groupData
.default !== undefined ) {
348 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
352 // This is only true for single_option group
353 // We assume these are the only groups that will allow for
354 // arbitrary, since it doesn't make any sense for the other
356 arbitraryValues
.forEach( function ( val
) {
358 // If the group allows for arbitrary data
359 groupData
.allowArbitrary
&&
360 // and it is single_option (or string_options, but we
361 // don't have cases of those yet, nor do we plan to)
362 groupData
.type
=== 'single_option' &&
363 // and, if there is a validate method and it passes on
365 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
366 // but if that value isn't already in the definition
368 .map( function ( filterData
) {
369 return String( filterData
.name
);
371 .indexOf( String( val
) ) === -1
373 // Add the filter information
374 groupData
.filters
.push( controller
._createFilterDataFromNumber(
376 groupData
.numToLabelFunc
?
377 groupData
.numToLabelFunc( val
) :
381 // If there's a sort function set up, re-sort the values
382 if ( groupData
.sortFunc
) {
383 groupData
.filters
.sort( groupData
.sortFunc
);
390 * Switch the view of the filters model
392 * @param {string} view Requested view
394 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
395 this.filtersModel
.switchView( view
);
399 * Reset to default filters
401 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
402 var params
= this._getDefaultParams();
403 if ( this.applyParamChange( params
) ) {
404 // Only update the changes list if there was a change to actual filters
405 this.updateChangesList();
407 this.uriProcessor
.updateURL( params
);
412 * Check whether the default values of the filters are all false.
414 * @return {boolean} Defaults are all false
416 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
417 return $.isEmptyObject( this._getDefaultParams( true ) );
421 * Empty all selected filters
423 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
424 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
425 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
427 if ( this.applyParamChange( {} ) ) {
428 // Only update the changes list if there was a change to actual filters
429 this.updateChangesList();
431 this.uriProcessor
.updateURL();
434 if ( highlightedFilterNames
) {
435 this._trackHighlight( 'clearAll', highlightedFilterNames
);
440 * Update the selected state of a filter
442 * @param {string} filterName Filter name
443 * @param {boolean} [isSelected] Filter selected state
445 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
446 var filterItem
= this.filtersModel
.getItemByName( filterName
);
449 // If no filter was found, break
453 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
455 if ( filterItem
.isSelected() !== isSelected
) {
456 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
458 this.updateChangesList();
460 // Check filter interactions
461 this.filtersModel
.reassessFilterInteractions( filterItem
);
466 * Clear both highlight and selection of a filter
468 * @param {string} filterName Name of the filter item
470 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
471 var filterItem
= this.filtersModel
.getItemByName( filterName
),
472 isHighlighted
= filterItem
.isHighlighted(),
473 isSelected
= filterItem
.isSelected();
475 if ( isSelected
|| isHighlighted
) {
476 this.filtersModel
.clearHighlightColor( filterName
);
477 this.filtersModel
.toggleFilterSelected( filterName
, false );
480 // Only update the changes list if the filter changed
481 // its selection state. If it only changed its highlight
483 this.updateChangesList();
486 this.filtersModel
.reassessFilterInteractions( filterItem
);
488 // Log filter grouping
489 this.trackFilterGroupings( 'removefilter' );
492 if ( isHighlighted
) {
493 this._trackHighlight( 'clear', filterName
);
498 * Toggle the highlight feature on and off
500 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
501 this.filtersModel
.toggleHighlight();
502 this.uriProcessor
.updateURL();
504 if ( this.filtersModel
.isHighlightEnabled() ) {
505 mw
.hook( 'RcFilters.highlight.enable' ).fire();
510 * Toggle the namespaces inverted feature on and off
512 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
513 this.filtersModel
.toggleInvertedNamespaces();
516 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
517 function ( filterItem
) { return filterItem
.isSelected(); }
520 // Only re-fetch results if there are namespace items that are actually selected
521 this.updateChangesList();
526 * Set the highlight color for a filter item
528 * @param {string} filterName Name of the filter item
529 * @param {string} color Selected color
531 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
532 this.filtersModel
.setHighlightColor( filterName
, color
);
533 this.uriProcessor
.updateURL();
534 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
538 * Clear highlight for a filter item
540 * @param {string} filterName Name of the filter item
542 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
543 this.filtersModel
.clearHighlightColor( filterName
);
544 this.uriProcessor
.updateURL();
545 this._trackHighlight( 'clear', filterName
);
549 * Enable or disable live updates.
550 * @param {boolean} enable True to enable, false to disable
552 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
553 this.changesListModel
.toggleLiveUpdate( enable
);
554 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
555 this.updateChangesList( null, this.LIVE_UPDATE
);
560 * Set a timeout for the next live update.
563 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
564 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
568 * Perform a live update.
571 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
572 if ( !this._shouldCheckForNewChanges() ) {
573 // skip this turn and check back later
574 this._scheduleLiveUpdate();
578 this._checkForNewChanges()
579 .then( function ( newChanges
) {
580 if ( !this._shouldCheckForNewChanges() ) {
581 // by the time the response is received,
582 // it may not be appropriate anymore
587 if ( this.changesListModel
.getLiveUpdate() ) {
588 return this.updateChangesList( null, this.LIVE_UPDATE
);
590 this.changesListModel
.setNewChangesExist( true );
594 .always( this._scheduleLiveUpdate
.bind( this ) );
598 * @return {boolean} It's appropriate to check for new changes now
601 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
602 return !document
.hidden
&&
603 !this.filtersModel
.hasConflict() &&
604 !this.changesListModel
.getNewChangesExist() &&
605 !this.updatingChangesList
&&
606 this.changesListModel
.getNextFrom();
610 * Check if new changes, newer than those currently shown, are available
612 * @return {jQuery.Promise} Promise object that resolves with a bool
613 * specifying if there are new changes or not
617 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
620 peek
: 1, // bypasses ChangesList specific UI
621 from: this.changesListModel
.getNextFrom()
623 return this._queryChangesList( 'liveUpdate', params
).then(
625 // no result is 204 with the 'peek' param
626 return data
.status
=== 200;
632 * Show the new changes
634 * @return {jQuery.Promise} Promise object that resolves after
635 * fetching and showing the new changes
637 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
638 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
642 * Save the current model state as a saved query
644 * @param {string} [label] Label of the saved query
645 * @param {boolean} [setAsDefault=false] This query should be set as the default
647 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
649 this.savedQueriesModel
.addNewQuery(
650 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
651 this.filtersModel
.getCurrentParameterState( true ),
656 this._saveSavedQueries();
660 * Remove a saved query
662 * @param {string} queryID Query id
664 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
665 this.savedQueriesModel
.removeQuery( queryID
);
667 this._saveSavedQueries();
671 * Rename a saved query
673 * @param {string} queryID Query id
674 * @param {string} newLabel New label for the query
676 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
677 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
680 queryItem
.updateLabel( newLabel
);
682 this._saveSavedQueries();
686 * Set a saved query as default
688 * @param {string} queryID Query Id. If null is given, default
691 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
692 this.savedQueriesModel
.setDefault( queryID
);
693 this._saveSavedQueries();
699 * @param {string} queryID Query id
701 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
702 var currentMatchingQuery
,
703 params
= this.savedQueriesModel
.getItemParams( queryID
);
705 currentMatchingQuery
= this.findQueryMatchingCurrentState();
708 currentMatchingQuery
&&
709 currentMatchingQuery
.getID() === queryID
711 // If the query we want to load is the one that is already
712 // loaded, don't reload it
716 if ( this.applyParamChange( params
) ) {
717 // Update changes list only if there was a difference in filter selection
718 this.updateChangesList();
720 this.uriProcessor
.updateURL( params
);
723 // Log filter grouping
724 this.trackFilterGroupings( 'savedfilters' );
728 * Check whether the current filter and highlight state exists
729 * in the saved queries model.
731 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
733 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
734 return this.savedQueriesModel
.findMatchingQuery(
735 this.filtersModel
.getCurrentParameterState( true )
740 * Save the current state of the saved queries model with all
741 * query item representation in the user settings.
743 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
744 var stringified
, oldPrefValue
,
745 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
746 state
= this.savedQueriesModel
.getState();
749 stringified
= JSON
.stringify( state
);
751 if ( $.byteLength( stringified
) > 65535 ) {
752 // Sanity check, since the preference can only hold that.
756 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
757 // The queries were converted from the previous version
758 // Keep the old string in the [prefname]-versionbackup
759 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
761 // Save the old preference in the backup preference
762 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
763 // Update the preference for this session
764 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
767 // Save the preference
768 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
769 // Update the preference for this session
770 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
772 // Tag as already saved so we don't do this again
773 this.wereSavedQueriesSaved
= true;
777 * Update sticky preferences with current model state
779 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
780 // Update default sticky values with selected, whether they came from
781 // the initial defaults or from the URL value that is being normalized
782 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
783 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
785 // TODO: Make these automatic by having the model go over sticky
786 // items and update their default values automatically
790 * Update the limit default value
792 * @param {number} newValue New value
794 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
795 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
799 * Update the days default value
801 * @param {number} newValue New value
803 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
804 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
808 * Update the group by page default value
810 * @param {boolean} newValue New value
812 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
813 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
817 * Update a numeric preference with a new value
819 * @param {string} prefName Preference name
820 * @param {number|string} newValue New value
822 mw
.rcfilters
.Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
823 if ( !$.isNumeric( newValue
) ) {
827 newValue
= Number( newValue
);
829 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
830 // Save the preference
831 new mw
.Api().saveOption( prefName
, newValue
);
832 // Update the preference for this session
833 mw
.user
.options
.set( prefName
, newValue
);
838 * Synchronize the URL with the current state of the filters
839 * without adding an history entry.
841 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
842 this.uriProcessor
.updateURL();
846 * Update filter state (selection and highlighting) based
847 * on current URL values.
849 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
850 * list based on the updated model.
852 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
853 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
855 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
857 // Update the sticky preferences, in case we received a value
859 this.updateStickyPreferences();
861 // Only update and fetch new results if it is requested
862 if ( fetchChangesList
) {
863 this.updateChangesList();
868 * Update the list of changes and notify the model
870 * @param {Object} [params] Extra parameters to add to the API call
871 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
872 * @return {jQuery.Promise} Promise that is resolved when the update is complete
874 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
875 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
877 if ( updateMode
=== this.FILTER_CHANGE
) {
878 this.uriProcessor
.updateURL( params
);
880 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
881 this.changesListModel
.invalidate();
883 this.changesListModel
.setNewChangesExist( false );
884 this.updatingChangesList
= true;
885 return this._fetchChangesList()
888 function ( pieces
) {
889 var $changesListContent
= pieces
.changes
,
890 $fieldset
= pieces
.fieldset
;
891 this.changesListModel
.update(
894 pieces
.noResultsDetails
,
896 // separator between old and new changes
897 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
900 // Do nothing for failure
902 .always( function () {
903 this.updatingChangesList
= false;
908 * Get an object representing the default parameter state, whether
909 * it is from the model defaults or from the saved queries.
911 * @param {boolean} [excludeHiddenParams] Exclude hidden and sticky params
912 * @return {Object} Default parameters
914 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function ( excludeHiddenParams
) {
915 if ( this.savedQueriesModel
.getDefault() ) {
916 return this.savedQueriesModel
.getDefaultParams( excludeHiddenParams
);
918 return this.filtersModel
.getDefaultParams( excludeHiddenParams
);
923 * Query the list of changes from the server for the current filters
925 * @param {string} counterId Id for this request. To allow concurrent requests
926 * not to invalidate each other.
927 * @param {Object} [params={}] Parameters to add to the query
929 * @return {jQuery.Promise} Promise object resolved with { content, status }
931 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
932 var uri
= this.uriProcessor
.getUpdatedUri(),
933 stickyParams
= this.filtersModel
.getStickyParamsValues(),
937 params
= params
|| {};
938 params
.action
= 'render'; // bypasses MW chrome
940 uri
.extend( params
);
942 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
943 requestId
= ++this.requestCounter
[ counterId
];
944 latestRequest = function () {
945 return requestId
=== this.requestCounter
[ counterId
];
948 // Sticky parameters override the URL params
949 // this is to make sure that whether we represent
950 // the sticky params in the URL or not (they may
951 // be normalized out) the sticky parameters are
952 // always being sent to the server with their
953 // current/default values
954 uri
.extend( stickyParams
);
956 return $.ajax( uri
.toString(), { contentType
: 'html' } )
958 function ( content
, message
, jqXHR
) {
959 if ( !latestRequest() ) {
960 return $.Deferred().reject();
967 // RC returns 404 when there is no results
969 if ( latestRequest() ) {
970 return $.Deferred().resolve(
972 content
: jqXHR
.responseText
,
982 * Fetch the list of changes from the server for the current filters
984 * @return {jQuery.Promise} Promise object that will resolve with the changes list
987 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
988 return this._queryChangesList( 'updateChangesList' )
993 // Status code 0 is not HTTP status code,
994 // but is valid value of XMLHttpRequest status.
995 // It is used for variety of network errors, for example
996 // when an AJAX call was cancelled before getting the response
997 if ( data
&& data
.status
=== 0 ) {
999 changes
: 'NO_RESULTS',
1000 // We need empty result set, to avoid exceptions because of undefined value
1002 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1006 $parsed
= $( '<div>' ).append( $( $.parseHTML( data
.content
) ) );
1008 return this._extractChangesListInfo( $parsed
);
1015 * Track usage of highlight feature
1017 * @param {string} action
1018 * @param {Array|Object|string} filters
1020 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1021 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1022 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1024 'event.ChangesListHighlights',
1028 userId
: mw
.user
.getId()
1034 * Track filter grouping usage
1036 * @param {string} action Action taken
1038 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1039 var controller
= this,
1040 rightNow
= new Date().getTime(),
1041 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1042 // Get all current filters
1043 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1044 return item
.getName();
1047 action
= action
|| 'filtermenu';
1049 // Check if these filters were the ones we just logged previously
1050 // (Don't log the same grouping twice, in case the user opens/closes)
1051 // the menu without action, or with the same result
1053 // Only log if the two arrays are different in size
1054 filters
.length
!== this.prevLoggedItems
.length
||
1055 // Or if any filters are not the same as the cached filters
1056 filters
.some( function ( filterName
) {
1057 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1059 // Or if any cached filters are not the same as given filters
1060 this.prevLoggedItems
.some( function ( filterName
) {
1061 return filters
.indexOf( filterName
) === -1;
1064 filters
.forEach( function ( filterName
) {
1066 'event.ChangesListFilterGrouping',
1069 groupIdentifier
: randomIdentifier
,
1071 userId
: mw
.user
.getId()
1076 // Cache the filter names
1077 this.prevLoggedItems
= filters
;
1082 * Apply a change of parameters to the model state, and check whether
1083 * the new state is different than the old state.
1085 * @param {Object} newParamState New parameter state to apply
1086 * @return {boolean} New applied model state is different than the previous state
1088 mw
.rcfilters
.Controller
.prototype.applyParamChange = function ( newParamState
) {
1090 before
= this.filtersModel
.getSelectedState();
1092 this.filtersModel
.updateStateFromParams( newParamState
);
1094 after
= this.filtersModel
.getSelectedState();
1096 return !OO
.compare( before
, after
);
1100 * Mark all changes as seen on Watchlist
1102 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1103 var api
= new mw
.Api();
1104 api
.postWithToken( 'csrf', {
1106 action
: 'setnotificationtimestamp',
1107 entirewatchlist
: true
1108 } ).then( function () {
1109 this.updateChangesList( null, 'markSeen' );
1112 }( mediaWiki
, jQuery
) );