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
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
;
20 this.requestCounter
= {};
21 this.baseFilterState
= {};
22 this.uriProcessor
= null;
23 this.initializing
= false;
24 this.wereSavedQueriesSaved
= false;
26 this.prevLoggedItems
= [];
28 this.FILTER_CHANGE
= 'filterChange';
29 this.SHOW_NEW_CHANGES
= 'showNewChanges';
30 this.LIVE_UPDATE
= 'liveUpdate';
34 OO
.initClass( mw
.rcfilters
.Controller
);
37 * Initialize the filter and parameter states
39 * @param {Array} filterStructure Filter definition and structure for the model
40 * @param {Object} [namespaceStructure] Namespace definition
41 * @param {Object} [tagList] Tag definition
43 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
44 var parsedSavedQueries
,
45 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
46 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
51 $changesList
= $( '.mw-changeslist' ).first().contents();
54 if ( namespaceStructure
) {
56 $.each( namespaceStructure
, function ( namespaceID
, label
) {
57 // Build and clean up the individual namespace items definition
60 label
: label
|| mw
.msg( 'blanknamespace' ),
63 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
66 cssClass
: 'mw-changeslist-ns-' + namespaceID
71 title
: mw
.msg( 'namespaces' ),
74 // Group definition (single group)
75 name
: 'namespace', // parameter name is singular
76 type
: 'string_options',
77 title
: mw
.msg( 'namespaces' ),
78 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
96 title
: mw
.msg( 'rcfilters-view-tags' ),
99 // Group definition (single group)
100 name
: 'tagfilter', // Parameter name
101 type
: 'string_options',
102 title
: 'rcfilters-view-tags', // Message key
103 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
111 // Add parameter range operations
116 type
: 'single_option',
117 title
: '', // Because it's a hidden group, this title actually appears nowhere
119 allowArbitrary
: true,
120 validate
: $.isNumeric
,
122 min
: 0, // The server normalizes negative numbers to 0 results
125 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
126 'default': displayConfig
.limitDefault
,
127 // Temporarily making this not sticky until we resolve the problem
128 // with the misleading preference. Note that if this is to be permanent
129 // we should remove all sticky behavior methods completely
132 excludedFromSavedQueries
: true,
133 filters
: displayConfig
.limitArray
.map( function ( num
) {
134 return controller
._createFilterDataFromNumber( num
, num
);
139 type
: 'single_option',
140 title
: '', // Because it's a hidden group, this title actually appears nowhere
142 allowArbitrary
: true,
143 validate
: $.isNumeric
,
146 max
: displayConfig
.maxDays
148 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
149 numToLabelFunc: function ( i
) {
150 return Number( i
) < 1 ?
151 ( Number( i
) * 24 ).toFixed( 2 ) :
154 'default': displayConfig
.daysDefault
,
155 // Temporarily making this not sticky while limit is not sticky, see above
157 excludedFromSavedQueries
: true,
159 // Hours (1, 2, 6, 12)
160 0.04166, 0.0833, 0.25, 0.5
162 ].concat( displayConfig
.daysArray
)
163 .map( function ( num
) {
164 return controller
._createFilterDataFromNumber(
166 // Convert fractions of days to number of hours for the labels
167 num
< 1 ? Math
.round( num
* 24 ) : num
179 title
: '', // Because it's a hidden group, this title actually appears nowhere
185 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
192 // Before we do anything, we need to see if we require additional items in the
193 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
194 // groups; if we ever expand it, this might need further generalization:
195 $.each( views
, function ( viewName
, viewData
) {
196 viewData
.groups
.forEach( function ( groupData
) {
197 var extraValues
= [];
198 if ( groupData
.allowArbitrary
) {
199 // If the value in the URI isn't in the group, add it
200 if ( uri
.query
[ groupData
.name
] !== undefined ) {
201 extraValues
.push( uri
.query
[ groupData
.name
] );
203 // If the default value isn't in the group, add it
204 if ( groupData
.default !== undefined ) {
205 extraValues
.push( String( groupData
.default ) );
207 controller
.addNumberValuesToGroup( groupData
, extraValues
);
212 // Initialize the model
213 this.filtersModel
.initializeFilters( filterStructure
, views
);
215 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
219 if ( !mw
.user
.isAnon() ) {
221 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
223 parsedSavedQueries
= {};
226 // Initialize saved queries
227 this.savedQueriesModel
.initialize( parsedSavedQueries
);
228 if ( this.savedQueriesModel
.isConverted() ) {
229 // Since we know we converted, we're going to re-save
230 // the queries so they are now migrated to the new format
231 this._saveSavedQueries();
235 // Check whether we need to load defaults.
236 // We do this by checking whether the current URI query
237 // contains any parameters recognized by the system.
238 // If it does, we load the given state.
239 // If it doesn't, we have no values at all, and we assume
240 // the user loads the base-page and we load defaults.
241 // Defaults should only be applied on load (if necessary)
243 this.initializing
= true;
245 if ( defaultSavedQueryExists
) {
246 // This came from the server, meaning that we have a default
247 // saved query, but the server could not load it, probably because
248 // it was pre-conversion to the new format.
249 // We need to load this query again
250 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
252 // There are either recognized parameters in the URL
253 // or there are none, but there is also no default
254 // saved query (so defaults are from the backend)
255 // We want to update the state but not fetch results
257 this.updateStateFromUrl( false );
259 // Update the changes list with the existing data
260 // so it gets processed
261 this.changesListModel
.update(
262 $changesList
.length
? $changesList
: 'NO_RESULTS',
263 $( 'fieldset.cloptions' ).first(),
264 true // We're using existing DOM elements
268 this.initializing
= false;
269 this.switchView( 'default' );
271 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
272 if ( this.pollingRate
) {
273 this._scheduleLiveUpdate();
278 * Create filter data from a number, for the filters that are numerical value
280 * @param {Number} num Number
281 * @param {Number} numForDisplay Number for the label
282 * @return {Object} Filter data
284 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
287 label
: mw
.language
.convertNumber( numForDisplay
)
292 * Add an arbitrary values to groups that allow arbitrary values
294 * @param {Object} groupData Group data
295 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
297 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
298 var controller
= this,
299 normalizeWithinRange = function ( range
, val
) {
300 if ( val
< range
.min
) {
301 return range
.min
; // Min
302 } else if ( val
>= range
.max
) {
303 return range
.max
; // Max
308 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
310 // Normalize the arbitrary values and the default value for a range
311 if ( groupData
.range
) {
312 arbitraryValues
= arbitraryValues
.map( function ( val
) {
313 return normalizeWithinRange( groupData
.range
, val
);
316 // Normalize the default, since that's user defined
317 if ( groupData
.default !== undefined ) {
318 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
322 // This is only true for single_option group
323 // We assume these are the only groups that will allow for
324 // arbitrary, since it doesn't make any sense for the other
326 arbitraryValues
.forEach( function ( val
) {
328 // If the group allows for arbitrary data
329 groupData
.allowArbitrary
&&
330 // and it is single_option (or string_options, but we
331 // don't have cases of those yet, nor do we plan to)
332 groupData
.type
=== 'single_option' &&
333 // and, if there is a validate method and it passes on
335 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
336 // but if that value isn't already in the definition
338 .map( function ( filterData
) {
339 return String( filterData
.name
);
341 .indexOf( String( val
) ) === -1
343 // Add the filter information
344 groupData
.filters
.push( controller
._createFilterDataFromNumber(
346 groupData
.numToLabelFunc
?
347 groupData
.numToLabelFunc( val
) :
351 // If there's a sort function set up, re-sort the values
352 if ( groupData
.sortFunc
) {
353 groupData
.filters
.sort( groupData
.sortFunc
);
360 * Switch the view of the filters model
362 * @param {string} view Requested view
364 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
365 this.filtersModel
.switchView( view
);
369 * Reset to default filters
371 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
372 this.filtersModel
.updateStateFromParams( this._getDefaultParams() );
374 this.updateChangesList();
378 * Check whether the default values of the filters are all false.
380 * @return {boolean} Defaults are all false
382 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
383 return $.isEmptyObject( this._getDefaultParams( true ) );
387 * Empty all selected filters
389 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
390 var highlightedFilterNames
= this.filtersModel
391 .getHighlightedItems()
392 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
394 this.filtersModel
.updateStateFromParams( {} );
396 this.updateChangesList();
398 if ( highlightedFilterNames
) {
399 this._trackHighlight( 'clearAll', highlightedFilterNames
);
404 * Update the selected state of a filter
406 * @param {string} filterName Filter name
407 * @param {boolean} [isSelected] Filter selected state
409 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
410 var filterItem
= this.filtersModel
.getItemByName( filterName
);
413 // If no filter was found, break
417 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
419 if ( filterItem
.isSelected() !== isSelected
) {
420 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
422 this.updateChangesList();
424 // Check filter interactions
425 this.filtersModel
.reassessFilterInteractions( filterItem
);
430 * Clear both highlight and selection of a filter
432 * @param {string} filterName Name of the filter item
434 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
435 var filterItem
= this.filtersModel
.getItemByName( filterName
),
436 isHighlighted
= filterItem
.isHighlighted(),
437 isSelected
= filterItem
.isSelected();
439 if ( isSelected
|| isHighlighted
) {
440 this.filtersModel
.clearHighlightColor( filterName
);
441 this.filtersModel
.toggleFilterSelected( filterName
, false );
444 // Only update the changes list if the filter changed
445 // its selection state. If it only changed its highlight
447 this.updateChangesList();
450 this.filtersModel
.reassessFilterInteractions( filterItem
);
452 // Log filter grouping
453 this.trackFilterGroupings( 'removefilter' );
456 if ( isHighlighted
) {
457 this._trackHighlight( 'clear', filterName
);
462 * Toggle the highlight feature on and off
464 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
465 this.filtersModel
.toggleHighlight();
466 this.uriProcessor
.updateURL();
468 if ( this.filtersModel
.isHighlightEnabled() ) {
469 mw
.hook( 'RcFilters.highlight.enable' ).fire();
474 * Toggle the namespaces inverted feature on and off
476 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
477 this.filtersModel
.toggleInvertedNamespaces();
480 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
481 function ( filterItem
) { return filterItem
.isSelected(); }
484 // Only re-fetch results if there are namespace items that are actually selected
485 this.updateChangesList();
490 * Set the highlight color for a filter item
492 * @param {string} filterName Name of the filter item
493 * @param {string} color Selected color
495 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
496 this.filtersModel
.setHighlightColor( filterName
, color
);
497 this.uriProcessor
.updateURL();
498 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
502 * Clear highlight for a filter item
504 * @param {string} filterName Name of the filter item
506 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
507 this.filtersModel
.clearHighlightColor( filterName
);
508 this.uriProcessor
.updateURL();
509 this._trackHighlight( 'clear', filterName
);
513 * Enable or disable live updates.
514 * @param {boolean} enable True to enable, false to disable
516 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
517 this.changesListModel
.toggleLiveUpdate( enable
);
518 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
519 this.updateChangesList( null, this.LIVE_UPDATE
);
524 * Set a timeout for the next live update.
527 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
528 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
532 * Perform a live update.
535 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
536 if ( !this._shouldCheckForNewChanges() ) {
537 // skip this turn and check back later
538 this._scheduleLiveUpdate();
542 this._checkForNewChanges()
543 .then( function ( newChanges
) {
544 if ( !this._shouldCheckForNewChanges() ) {
545 // by the time the response is received,
546 // it may not be appropriate anymore
551 if ( this.changesListModel
.getLiveUpdate() ) {
552 return this.updateChangesList( null, this.LIVE_UPDATE
);
554 this.changesListModel
.setNewChangesExist( true );
558 .always( this._scheduleLiveUpdate
.bind( this ) );
562 * @return {boolean} It's appropriate to check for new changes now
565 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
566 return !document
.hidden
&&
567 !this.filtersModel
.hasConflict() &&
568 !this.changesListModel
.getNewChangesExist() &&
569 !this.updatingChangesList
&&
570 this.changesListModel
.getNextFrom();
574 * Check if new changes, newer than those currently shown, are available
576 * @return {jQuery.Promise} Promise object that resolves with a bool
577 * specifying if there are new changes or not
581 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
584 peek
: 1, // bypasses ChangesList specific UI
585 from: this.changesListModel
.getNextFrom()
587 return this._queryChangesList( 'liveUpdate', params
).then(
589 // no result is 204 with the 'peek' param
590 return data
.status
=== 200;
596 * Show the new changes
598 * @return {jQuery.Promise} Promise object that resolves after
599 * fetching and showing the new changes
601 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
602 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
606 * Save the current model state as a saved query
608 * @param {string} [label] Label of the saved query
609 * @param {boolean} [setAsDefault=false] This query should be set as the default
611 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
613 this.savedQueriesModel
.addNewQuery(
614 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
615 this.filtersModel
.getCurrentParameterState( true ),
620 this._saveSavedQueries();
624 * Remove a saved query
626 * @param {string} queryID Query id
628 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
629 this.savedQueriesModel
.removeQuery( queryID
);
631 this._saveSavedQueries();
635 * Rename a saved query
637 * @param {string} queryID Query id
638 * @param {string} newLabel New label for the query
640 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
641 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
644 queryItem
.updateLabel( newLabel
);
646 this._saveSavedQueries();
650 * Set a saved query as default
652 * @param {string} queryID Query Id. If null is given, default
655 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
656 this.savedQueriesModel
.setDefault( queryID
);
657 this._saveSavedQueries();
663 * @param {string} queryID Query id
665 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
666 var currentMatchingQuery
,
667 params
= this.savedQueriesModel
.getItemParams( queryID
);
669 currentMatchingQuery
= this.findQueryMatchingCurrentState();
672 currentMatchingQuery
&&
673 currentMatchingQuery
.getID() === queryID
675 // If the query we want to load is the one that is already
676 // loaded, don't reload it
680 // Apply parameters to model
681 this.filtersModel
.updateStateFromParams( params
);
683 this.updateChangesList();
685 // Log filter grouping
686 this.trackFilterGroupings( 'savedfilters' );
690 * Check whether the current filter and highlight state exists
691 * in the saved queries model.
693 * @return {boolean} Query exists
695 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
696 return this.savedQueriesModel
.findMatchingQuery(
697 this.filtersModel
.getCurrentParameterState( true )
702 * Save the current state of the saved queries model with all
703 * query item representation in the user settings.
705 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
706 var stringified
, oldPrefValue
,
707 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
708 state
= this.savedQueriesModel
.getState();
711 stringified
= JSON
.stringify( state
);
713 if ( $.byteLength( stringified
) > 65535 ) {
714 // Sanity check, since the preference can only hold that.
718 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
719 // The queries were converted from the previous version
720 // Keep the old string in the [prefname]-versionbackup
721 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
723 // Save the old preference in the backup preference
724 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
725 // Update the preference for this session
726 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
729 // Save the preference
730 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
731 // Update the preference for this session
732 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
734 // Tag as already saved so we don't do this again
735 this.wereSavedQueriesSaved
= true;
739 * Update sticky preferences with current model state
741 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
742 // Update default sticky values with selected, whether they came from
743 // the initial defaults or from the URL value that is being normalized
744 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
745 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
747 // TODO: Make these automatic by having the model go over sticky
748 // items and update their default values automatically
752 * Update the limit default value
754 * param {number} newValue New value
756 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
757 // HACK: Temporarily remove this from being sticky
761 if ( !$.isNumeric( newValue ) ) {
765 newValue = Number( newValue );
767 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
768 // Save the preference
769 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
770 // Update the preference for this session
771 mw.user.options.set( 'rcfilters-rclimit', newValue );
778 * Update the days default value
780 * param {number} newValue New value
782 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
783 // HACK: Temporarily remove this from being sticky
787 if ( !$.isNumeric( newValue ) ) {
791 newValue = Number( newValue );
793 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
794 // Save the preference
795 new mw.Api().saveOption( 'rcdays', newValue );
796 // Update the preference for this session
797 mw.user.options.set( 'rcdays', newValue );
804 * Update the group by page default value
806 * @param {number} newValue New value
808 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
809 if ( !$.isNumeric( newValue
) ) {
813 newValue
= Number( newValue
);
815 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
816 // Save the preference
817 new mw
.Api().saveOption( 'usenewrc', newValue
);
818 // Update the preference for this session
819 mw
.user
.options
.set( 'usenewrc', newValue
);
824 * Synchronize the URL with the current state of the filters
825 * without adding an history entry.
827 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
828 this.uriProcessor
.replaceUpdatedUri();
832 * Update filter state (selection and highlighting) based
833 * on current URL values.
835 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
836 * list based on the updated model.
838 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
839 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
841 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
843 // Update the sticky preferences, in case we received a value
845 this.updateStickyPreferences();
847 // Only update and fetch new results if it is requested
848 if ( fetchChangesList
) {
849 this.updateChangesList();
854 * Update the list of changes and notify the model
856 * @param {Object} [params] Extra parameters to add to the API call
857 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
858 * @return {jQuery.Promise} Promise that is resolved when the update is complete
860 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
861 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
863 if ( updateMode
=== this.FILTER_CHANGE
) {
864 this.uriProcessor
.updateURL( params
);
866 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
867 this.changesListModel
.invalidate();
869 this.changesListModel
.setNewChangesExist( false );
870 this.updatingChangesList
= true;
871 return this._fetchChangesList()
874 function ( pieces
) {
875 var $changesListContent
= pieces
.changes
,
876 $fieldset
= pieces
.fieldset
;
877 this.changesListModel
.update(
881 // separator between old and new changes
882 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
885 // Do nothing for failure
887 .always( function () {
888 this.updatingChangesList
= false;
893 * Get an object representing the default parameter state, whether
894 * it is from the model defaults or from the saved queries.
896 * @param {boolean} [excludeHiddenParams] Exclude hidden and sticky params
897 * @return {Object} Default parameters
899 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function ( excludeHiddenParams
) {
900 if ( this.savedQueriesModel
.getDefault() ) {
901 return this.savedQueriesModel
.getDefaultParams( excludeHiddenParams
);
903 return this.filtersModel
.getDefaultParams( excludeHiddenParams
);
908 * Query the list of changes from the server for the current filters
910 * @param {string} counterId Id for this request. To allow concurrent requests
911 * not to invalidate each other.
912 * @param {Object} [params={}] Parameters to add to the query
914 * @return {jQuery.Promise} Promise object resolved with { content, status }
916 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
917 var uri
= this.uriProcessor
.getUpdatedUri(),
918 stickyParams
= this.filtersModel
.getStickyParamsValues(),
922 params
= params
|| {};
923 params
.action
= 'render'; // bypasses MW chrome
925 uri
.extend( params
);
927 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
928 requestId
= ++this.requestCounter
[ counterId
];
929 latestRequest = function () {
930 return requestId
=== this.requestCounter
[ counterId
];
933 // Sticky parameters override the URL params
934 // this is to make sure that whether we represent
935 // the sticky params in the URL or not (they may
936 // be normalized out) the sticky parameters are
937 // always being sent to the server with their
938 // current/default values
939 uri
.extend( stickyParams
);
941 return $.ajax( uri
.toString(), { contentType
: 'html' } )
943 function ( content
, message
, jqXHR
) {
944 if ( !latestRequest() ) {
945 return $.Deferred().reject();
952 // RC returns 404 when there is no results
954 if ( latestRequest() ) {
955 return $.Deferred().resolve(
957 content
: jqXHR
.responseText
,
967 * Fetch the list of changes from the server for the current filters
969 * @return {jQuery.Promise} Promise object that will resolve with the changes list
972 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
973 return this._queryChangesList( 'updateChangesList' )
976 var $parsed
= $( '<div>' ).append( $( $.parseHTML( data
.content
) ) ),
979 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
981 fieldset
: $parsed
.find( 'fieldset.cloptions' ).first()
984 if ( pieces
.changes
.length
=== 0 ) {
985 pieces
.changes
= 'NO_RESULTS';
994 * Track usage of highlight feature
996 * @param {string} action
997 * @param {Array|Object|string} filters
999 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1000 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1001 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1003 'event.ChangesListHighlights',
1007 userId
: mw
.user
.getId()
1013 * Track filter grouping usage
1015 * @param {string} action Action taken
1017 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1018 var controller
= this,
1019 rightNow
= new Date().getTime(),
1020 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1021 // Get all current filters
1022 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1023 return item
.getName();
1026 action
= action
|| 'filtermenu';
1028 // Check if these filters were the ones we just logged previously
1029 // (Don't log the same grouping twice, in case the user opens/closes)
1030 // the menu without action, or with the same result
1032 // Only log if the two arrays are different in size
1033 filters
.length
!== this.prevLoggedItems
.length
||
1034 // Or if any filters are not the same as the cached filters
1035 filters
.some( function ( filterName
) {
1036 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1038 // Or if any cached filters are not the same as given filters
1039 this.prevLoggedItems
.some( function ( filterName
) {
1040 return filters
.indexOf( filterName
) === -1;
1043 filters
.forEach( function ( filterName
) {
1045 'event.ChangesListFilterGrouping',
1048 groupIdentifier
: randomIdentifier
,
1050 userId
: mw
.user
.getId()
1055 // Cache the filter names
1056 this.prevLoggedItems
= filters
;
1061 * Mark all changes as seen on Watchlist
1063 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1064 var api
= new mw
.Api();
1065 api
.postWithToken( 'csrf', {
1067 action
: 'setnotificationtimestamp',
1068 entirewatchlist
: true
1069 } ).then( function () {
1070 this.updateChangesList( null, 'markSeen' );
1073 }( mediaWiki
, jQuery
) );