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 filters
: displayConfig
.limitArray
.map( function ( num
) {
132 return controller
._createFilterDataFromNumber( num
, num
);
137 type
: 'single_option',
138 title
: '', // Because it's a hidden group, this title actually appears nowhere
140 allowArbitrary
: true,
141 validate
: $.isNumeric
,
144 max
: displayConfig
.maxDays
146 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
147 numToLabelFunc: function ( i
) {
148 return Number( i
) < 1 ?
149 ( Number( i
) * 24 ).toFixed( 2 ) :
152 'default': mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
155 // Hours (1, 2, 6, 12)
156 0.04166, 0.0833, 0.25, 0.5
158 ].concat( displayConfig
.daysArray
)
159 .map( function ( num
) {
160 return controller
._createFilterDataFromNumber(
162 // Convert fractions of days to number of hours for the labels
163 num
< 1 ? Math
.round( num
* 24 ) : num
175 title
: '', // Because it's a hidden group, this title actually appears nowhere
181 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
188 // Before we do anything, we need to see if we require additional items in the
189 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
190 // groups; if we ever expand it, this might need further generalization:
191 $.each( views
, function ( viewName
, viewData
) {
192 viewData
.groups
.forEach( function ( groupData
) {
193 var extraValues
= [];
194 if ( groupData
.allowArbitrary
) {
195 // If the value in the URI isn't in the group, add it
196 if ( uri
.query
[ groupData
.name
] !== undefined ) {
197 extraValues
.push( uri
.query
[ groupData
.name
] );
199 // If the default value isn't in the group, add it
200 if ( groupData
.default !== undefined ) {
201 extraValues
.push( String( groupData
.default ) );
203 controller
.addNumberValuesToGroup( groupData
, extraValues
);
208 // Initialize the model
209 this.filtersModel
.initializeFilters( filterStructure
, views
);
211 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
215 if ( !mw
.user
.isAnon() ) {
217 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
219 parsedSavedQueries
= {};
222 // Initialize saved queries
223 this.savedQueriesModel
.initialize( parsedSavedQueries
);
224 if ( this.savedQueriesModel
.isConverted() ) {
225 // Since we know we converted, we're going to re-save
226 // the queries so they are now migrated to the new format
227 this._saveSavedQueries();
231 // Check whether we need to load defaults.
232 // We do this by checking whether the current URI query
233 // contains any parameters recognized by the system.
234 // If it does, we load the given state.
235 // If it doesn't, we have no values at all, and we assume
236 // the user loads the base-page and we load defaults.
237 // Defaults should only be applied on load (if necessary)
239 this.initializing
= true;
241 if ( defaultSavedQueryExists
) {
242 // This came from the server, meaning that we have a default
243 // saved query, but the server could not load it, probably because
244 // it was pre-conversion to the new format.
245 // We need to load this query again
246 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
248 // There are either recognized parameters in the URL
249 // or there are none, but there is also no default
250 // saved query (so defaults are from the backend)
251 // We want to update the state but not fetch results
253 this.updateStateFromUrl( false );
255 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
257 // Update the changes list with the existing data
258 // so it gets processed
259 this.changesListModel
.update(
262 pieces
.noResultsDetails
,
263 true // We're using existing DOM elements
267 this.initializing
= false;
268 this.switchView( 'default' );
270 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
271 if ( this.pollingRate
) {
272 this._scheduleLiveUpdate();
277 * Extracts information from the changes list DOM
279 * @param {jQuery} $root Root DOM to find children from
280 * @return {Object} Information about changes list
281 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
282 * (either normally or as an error)
283 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
284 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
285 * @return {jQuery} return.fieldset Fieldset
287 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
) {
289 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
290 areResults
= !!$changesListContents
.length
;
293 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
294 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
298 isTimeout
= !!$root
.find( '.mw-changeslist-timeout' ).length
;
299 info
.noResultsDetails
= isTimeout
? 'NO_RESULTS_TIMEOUT' : 'NO_RESULTS_NORMAL';
306 * Create filter data from a number, for the filters that are numerical value
308 * @param {Number} num Number
309 * @param {Number} numForDisplay Number for the label
310 * @return {Object} Filter data
312 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
315 label
: mw
.language
.convertNumber( numForDisplay
)
320 * Add an arbitrary values to groups that allow arbitrary values
322 * @param {Object} groupData Group data
323 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
325 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
326 var controller
= this,
327 normalizeWithinRange = function ( range
, val
) {
328 if ( val
< range
.min
) {
329 return range
.min
; // Min
330 } else if ( val
>= range
.max
) {
331 return range
.max
; // Max
336 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
338 // Normalize the arbitrary values and the default value for a range
339 if ( groupData
.range
) {
340 arbitraryValues
= arbitraryValues
.map( function ( val
) {
341 return normalizeWithinRange( groupData
.range
, val
);
344 // Normalize the default, since that's user defined
345 if ( groupData
.default !== undefined ) {
346 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
350 // This is only true for single_option group
351 // We assume these are the only groups that will allow for
352 // arbitrary, since it doesn't make any sense for the other
354 arbitraryValues
.forEach( function ( val
) {
356 // If the group allows for arbitrary data
357 groupData
.allowArbitrary
&&
358 // and it is single_option (or string_options, but we
359 // don't have cases of those yet, nor do we plan to)
360 groupData
.type
=== 'single_option' &&
361 // and, if there is a validate method and it passes on
363 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
364 // but if that value isn't already in the definition
366 .map( function ( filterData
) {
367 return String( filterData
.name
);
369 .indexOf( String( val
) ) === -1
371 // Add the filter information
372 groupData
.filters
.push( controller
._createFilterDataFromNumber(
374 groupData
.numToLabelFunc
?
375 groupData
.numToLabelFunc( val
) :
379 // If there's a sort function set up, re-sort the values
380 if ( groupData
.sortFunc
) {
381 groupData
.filters
.sort( groupData
.sortFunc
);
388 * Switch the view of the filters model
390 * @param {string} view Requested view
392 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
393 this.filtersModel
.switchView( view
);
397 * Reset to default filters
399 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
400 var params
= this._getDefaultParams();
401 if ( this.applyParamChange( params
) ) {
402 // Only update the changes list if there was a change to actual filters
403 this.updateChangesList();
405 this.uriProcessor
.updateURL( params
);
410 * Check whether the default values of the filters are all false.
412 * @return {boolean} Defaults are all false
414 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
415 return $.isEmptyObject( this._getDefaultParams() );
419 * Empty all selected filters
421 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
422 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
423 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
425 if ( this.applyParamChange( {} ) ) {
426 // Only update the changes list if there was a change to actual filters
427 this.updateChangesList();
429 this.uriProcessor
.updateURL();
432 if ( highlightedFilterNames
) {
433 this._trackHighlight( 'clearAll', highlightedFilterNames
);
438 * Update the selected state of a filter
440 * @param {string} filterName Filter name
441 * @param {boolean} [isSelected] Filter selected state
443 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
444 var filterItem
= this.filtersModel
.getItemByName( filterName
);
447 // If no filter was found, break
451 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
453 if ( filterItem
.isSelected() !== isSelected
) {
454 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
456 this.updateChangesList();
458 // Check filter interactions
459 this.filtersModel
.reassessFilterInteractions( filterItem
);
464 * Clear both highlight and selection of a filter
466 * @param {string} filterName Name of the filter item
468 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
469 var filterItem
= this.filtersModel
.getItemByName( filterName
),
470 isHighlighted
= filterItem
.isHighlighted(),
471 isSelected
= filterItem
.isSelected();
473 if ( isSelected
|| isHighlighted
) {
474 this.filtersModel
.clearHighlightColor( filterName
);
475 this.filtersModel
.toggleFilterSelected( filterName
, false );
478 // Only update the changes list if the filter changed
479 // its selection state. If it only changed its highlight
481 this.updateChangesList();
484 this.filtersModel
.reassessFilterInteractions( filterItem
);
486 // Log filter grouping
487 this.trackFilterGroupings( 'removefilter' );
490 if ( isHighlighted
) {
491 this._trackHighlight( 'clear', filterName
);
496 * Toggle the highlight feature on and off
498 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
499 this.filtersModel
.toggleHighlight();
500 this.uriProcessor
.updateURL();
502 if ( this.filtersModel
.isHighlightEnabled() ) {
503 mw
.hook( 'RcFilters.highlight.enable' ).fire();
508 * Toggle the namespaces inverted feature on and off
510 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
511 this.filtersModel
.toggleInvertedNamespaces();
514 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
515 function ( filterItem
) { return filterItem
.isSelected(); }
518 // Only re-fetch results if there are namespace items that are actually selected
519 this.updateChangesList();
524 * Set the highlight color for a filter item
526 * @param {string} filterName Name of the filter item
527 * @param {string} color Selected color
529 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
530 this.filtersModel
.setHighlightColor( filterName
, color
);
531 this.uriProcessor
.updateURL();
532 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
536 * Clear highlight for a filter item
538 * @param {string} filterName Name of the filter item
540 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
541 this.filtersModel
.clearHighlightColor( filterName
);
542 this.uriProcessor
.updateURL();
543 this._trackHighlight( 'clear', filterName
);
547 * Enable or disable live updates.
548 * @param {boolean} enable True to enable, false to disable
550 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
551 this.changesListModel
.toggleLiveUpdate( enable
);
552 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
553 this.updateChangesList( null, this.LIVE_UPDATE
);
558 * Set a timeout for the next live update.
561 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
562 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
566 * Perform a live update.
569 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
570 if ( !this._shouldCheckForNewChanges() ) {
571 // skip this turn and check back later
572 this._scheduleLiveUpdate();
576 this._checkForNewChanges()
577 .then( function ( newChanges
) {
578 if ( !this._shouldCheckForNewChanges() ) {
579 // by the time the response is received,
580 // it may not be appropriate anymore
585 if ( this.changesListModel
.getLiveUpdate() ) {
586 return this.updateChangesList( null, this.LIVE_UPDATE
);
588 this.changesListModel
.setNewChangesExist( true );
592 .always( this._scheduleLiveUpdate
.bind( this ) );
596 * @return {boolean} It's appropriate to check for new changes now
599 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
600 return !document
.hidden
&&
601 !this.filtersModel
.hasConflict() &&
602 !this.changesListModel
.getNewChangesExist() &&
603 !this.updatingChangesList
&&
604 this.changesListModel
.getNextFrom();
608 * Check if new changes, newer than those currently shown, are available
610 * @return {jQuery.Promise} Promise object that resolves with a bool
611 * specifying if there are new changes or not
615 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
618 peek
: 1, // bypasses ChangesList specific UI
619 from: this.changesListModel
.getNextFrom()
621 return this._queryChangesList( 'liveUpdate', params
).then(
623 // no result is 204 with the 'peek' param
624 return data
.status
=== 200;
630 * Show the new changes
632 * @return {jQuery.Promise} Promise object that resolves after
633 * fetching and showing the new changes
635 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
636 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
640 * Save the current model state as a saved query
642 * @param {string} [label] Label of the saved query
643 * @param {boolean} [setAsDefault=false] This query should be set as the default
645 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
647 this.savedQueriesModel
.addNewQuery(
648 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
649 this.filtersModel
.getCurrentParameterState( true ),
654 this._saveSavedQueries();
658 * Remove a saved query
660 * @param {string} queryID Query id
662 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
663 this.savedQueriesModel
.removeQuery( queryID
);
665 this._saveSavedQueries();
669 * Rename a saved query
671 * @param {string} queryID Query id
672 * @param {string} newLabel New label for the query
674 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
675 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
678 queryItem
.updateLabel( newLabel
);
680 this._saveSavedQueries();
684 * Set a saved query as default
686 * @param {string} queryID Query Id. If null is given, default
689 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
690 this.savedQueriesModel
.setDefault( queryID
);
691 this._saveSavedQueries();
697 * @param {string} queryID Query id
699 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
700 var currentMatchingQuery
,
701 params
= this.savedQueriesModel
.getItemParams( queryID
);
703 currentMatchingQuery
= this.findQueryMatchingCurrentState();
706 currentMatchingQuery
&&
707 currentMatchingQuery
.getID() === queryID
709 // If the query we want to load is the one that is already
710 // loaded, don't reload it
714 if ( this.applyParamChange( params
) ) {
715 // Update changes list only if there was a difference in filter selection
716 this.updateChangesList();
718 this.uriProcessor
.updateURL( params
);
721 // Log filter grouping
722 this.trackFilterGroupings( 'savedfilters' );
726 * Check whether the current filter and highlight state exists
727 * in the saved queries model.
729 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
731 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
732 return this.savedQueriesModel
.findMatchingQuery(
733 this.filtersModel
.getCurrentParameterState( true )
738 * Save the current state of the saved queries model with all
739 * query item representation in the user settings.
741 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
742 var stringified
, oldPrefValue
,
743 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
744 state
= this.savedQueriesModel
.getState();
747 stringified
= JSON
.stringify( state
);
749 if ( $.byteLength( stringified
) > 65535 ) {
750 // Sanity check, since the preference can only hold that.
754 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
755 // The queries were converted from the previous version
756 // Keep the old string in the [prefname]-versionbackup
757 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
759 // Save the old preference in the backup preference
760 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
761 // Update the preference for this session
762 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
765 // Save the preference
766 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
767 // Update the preference for this session
768 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
770 // Tag as already saved so we don't do this again
771 this.wereSavedQueriesSaved
= true;
775 * Update sticky preferences with current model state
777 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
778 // Update default sticky values with selected, whether they came from
779 // the initial defaults or from the URL value that is being normalized
780 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
781 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
783 // TODO: Make these automatic by having the model go over sticky
784 // items and update their default values automatically
788 * Update the limit default value
790 * @param {number} newValue New value
792 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
793 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
797 * Update the days default value
799 * @param {number} newValue New value
801 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
802 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
806 * Update the group by page default value
808 * @param {boolean} newValue New value
810 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
811 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
815 * Update a numeric preference with a new value
817 * @param {string} prefName Preference name
818 * @param {number|string} newValue New value
820 mw
.rcfilters
.Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
821 if ( !$.isNumeric( newValue
) ) {
825 newValue
= Number( newValue
);
827 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
828 // Save the preference
829 new mw
.Api().saveOption( prefName
, newValue
);
830 // Update the preference for this session
831 mw
.user
.options
.set( prefName
, newValue
);
836 * Synchronize the URL with the current state of the filters
837 * without adding an history entry.
839 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
840 this.uriProcessor
.updateURL();
844 * Update filter state (selection and highlighting) based
845 * on current URL values.
847 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
848 * list based on the updated model.
850 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
851 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
853 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
855 // Update the sticky preferences, in case we received a value
857 this.updateStickyPreferences();
859 // Only update and fetch new results if it is requested
860 if ( fetchChangesList
) {
861 this.updateChangesList();
866 * Update the list of changes and notify the model
868 * @param {Object} [params] Extra parameters to add to the API call
869 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
870 * @return {jQuery.Promise} Promise that is resolved when the update is complete
872 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
873 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
875 if ( updateMode
=== this.FILTER_CHANGE
) {
876 this.uriProcessor
.updateURL( params
);
878 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
879 this.changesListModel
.invalidate();
881 this.changesListModel
.setNewChangesExist( false );
882 this.updatingChangesList
= true;
883 return this._fetchChangesList()
886 function ( pieces
) {
887 var $changesListContent
= pieces
.changes
,
888 $fieldset
= pieces
.fieldset
;
889 this.changesListModel
.update(
892 pieces
.noResultsDetails
,
894 // separator between old and new changes
895 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
898 // Do nothing for failure
900 .always( function () {
901 this.updatingChangesList
= false;
906 * Get an object representing the default parameter state, whether
907 * it is from the model defaults or from the saved queries.
909 * @return {Object} Default parameters
911 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
912 if ( this.savedQueriesModel
.getDefault() ) {
913 return this.savedQueriesModel
.getDefaultParams();
915 return this.filtersModel
.getDefaultParams();
920 * Query the list of changes from the server for the current filters
922 * @param {string} counterId Id for this request. To allow concurrent requests
923 * not to invalidate each other.
924 * @param {Object} [params={}] Parameters to add to the query
926 * @return {jQuery.Promise} Promise object resolved with { content, status }
928 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
929 var uri
= this.uriProcessor
.getUpdatedUri(),
930 stickyParams
= this.filtersModel
.getStickyParamsValues(),
934 params
= params
|| {};
935 params
.action
= 'render'; // bypasses MW chrome
937 uri
.extend( params
);
939 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
940 requestId
= ++this.requestCounter
[ counterId
];
941 latestRequest = function () {
942 return requestId
=== this.requestCounter
[ counterId
];
945 // Sticky parameters override the URL params
946 // this is to make sure that whether we represent
947 // the sticky params in the URL or not (they may
948 // be normalized out) the sticky parameters are
949 // always being sent to the server with their
950 // current/default values
951 uri
.extend( stickyParams
);
953 return $.ajax( uri
.toString(), { contentType
: 'html' } )
955 function ( content
, message
, jqXHR
) {
956 if ( !latestRequest() ) {
957 return $.Deferred().reject();
964 // RC returns 404 when there is no results
966 if ( latestRequest() ) {
967 return $.Deferred().resolve(
969 content
: jqXHR
.responseText
,
979 * Fetch the list of changes from the server for the current filters
981 * @return {jQuery.Promise} Promise object that will resolve with the changes list
984 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
985 return this._queryChangesList( 'updateChangesList' )
990 // Status code 0 is not HTTP status code,
991 // but is valid value of XMLHttpRequest status.
992 // It is used for variety of network errors, for example
993 // when an AJAX call was cancelled before getting the response
994 if ( data
&& data
.status
=== 0 ) {
996 changes
: 'NO_RESULTS',
997 // We need empty result set, to avoid exceptions because of undefined value
999 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1003 $parsed
= $( '<div>' ).append( $( $.parseHTML( data
.content
) ) );
1005 return this._extractChangesListInfo( $parsed
);
1012 * Track usage of highlight feature
1014 * @param {string} action
1015 * @param {Array|Object|string} filters
1017 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1018 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1019 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1021 'event.ChangesListHighlights',
1025 userId
: mw
.user
.getId()
1031 * Track filter grouping usage
1033 * @param {string} action Action taken
1035 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1036 var controller
= this,
1037 rightNow
= new Date().getTime(),
1038 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1039 // Get all current filters
1040 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1041 return item
.getName();
1044 action
= action
|| 'filtermenu';
1046 // Check if these filters were the ones we just logged previously
1047 // (Don't log the same grouping twice, in case the user opens/closes)
1048 // the menu without action, or with the same result
1050 // Only log if the two arrays are different in size
1051 filters
.length
!== this.prevLoggedItems
.length
||
1052 // Or if any filters are not the same as the cached filters
1053 filters
.some( function ( filterName
) {
1054 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1056 // Or if any cached filters are not the same as given filters
1057 this.prevLoggedItems
.some( function ( filterName
) {
1058 return filters
.indexOf( filterName
) === -1;
1061 filters
.forEach( function ( filterName
) {
1063 'event.ChangesListFilterGrouping',
1066 groupIdentifier
: randomIdentifier
,
1068 userId
: mw
.user
.getId()
1073 // Cache the filter names
1074 this.prevLoggedItems
= filters
;
1079 * Apply a change of parameters to the model state, and check whether
1080 * the new state is different than the old state.
1082 * @param {Object} newParamState New parameter state to apply
1083 * @return {boolean} New applied model state is different than the previous state
1085 mw
.rcfilters
.Controller
.prototype.applyParamChange = function ( newParamState
) {
1087 before
= this.filtersModel
.getSelectedState();
1089 this.filtersModel
.updateStateFromParams( newParamState
);
1091 after
= this.filtersModel
.getSelectedState();
1093 return !OO
.compare( before
, after
);
1097 * Mark all changes as seen on Watchlist
1099 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1100 var api
= new mw
.Api();
1101 api
.postWithToken( 'csrf', {
1103 action
: 'setnotificationtimestamp',
1104 entirewatchlist
: true
1105 } ).then( function () {
1106 this.updateChangesList( null, 'markSeen' );
1109 }( mediaWiki
, jQuery
) );