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' ),
50 $changesList
= $( '.mw-changeslist' ).first().contents();
53 if ( namespaceStructure
) {
55 $.each( namespaceStructure
, function ( namespaceID
, label
) {
56 // Build and clean up the individual namespace items definition
59 label
: label
|| mw
.msg( 'blanknamespace' ),
62 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
65 cssClass
: 'mw-changeslist-ns-' + namespaceID
70 title
: mw
.msg( 'namespaces' ),
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' },
86 title
: mw
.msg( 'rcfilters-view-tags' ),
89 // Group definition (single group)
90 name
: 'tagfilter', // Parameter name
91 type
: 'string_options',
92 title
: 'rcfilters-view-tags', // Message key
93 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
101 // Add parameter range operations
106 type
: 'single_option',
107 title
: '', // Because it's a hidden group, this title actually appears nowhere
109 allowArbitrary
: true,
110 validate
: $.isNumeric
,
112 min
: 0, // The server normalizes negative numbers to 0 results
115 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
116 'default': displayConfig
.limitDefault
,
117 // Temporarily making this not sticky until we resolve the problem
118 // with the misleading preference. Note that if this is to be permanent
119 // we should remove all sticky behavior methods completely
122 excludedFromSavedQueries
: true,
123 filters
: displayConfig
.limitArray
.map( function ( num
) {
124 return controller
._createFilterDataFromNumber( num
, num
);
129 type
: 'single_option',
130 title
: '', // Because it's a hidden group, this title actually appears nowhere
132 allowArbitrary
: true,
133 validate
: $.isNumeric
,
136 max
: displayConfig
.maxDays
138 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
139 numToLabelFunc: function ( i
) {
140 return Number( i
) < 1 ?
141 ( Number( i
) * 24 ).toFixed( 2 ) :
144 'default': displayConfig
.daysDefault
,
145 // Temporarily making this not sticky while limit is not sticky, see above
147 excludedFromSavedQueries
: true,
149 // Hours (1, 2, 6, 12)
150 0.04166, 0.0833, 0.25, 0.5
152 ].concat( displayConfig
.daysArray
)
153 .map( function ( num
) {
154 return controller
._createFilterDataFromNumber(
156 // Convert fractions of days to number of hours for the labels
157 num
< 1 ? Math
.round( num
* 24 ) : num
169 title
: '', // Because it's a hidden group, this title actually appears nowhere
175 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
182 // Before we do anything, we need to see if we require additional items in the
183 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
184 // groups; if we ever expand it, this might need further generalization:
185 $.each( views
, function ( viewName
, viewData
) {
186 viewData
.groups
.forEach( function ( groupData
) {
187 var extraValues
= [];
188 if ( groupData
.allowArbitrary
) {
189 // If the value in the URI isn't in the group, add it
190 if ( uri
.query
[ groupData
.name
] !== undefined ) {
191 extraValues
.push( uri
.query
[ groupData
.name
] );
193 // If the default value isn't in the group, add it
194 if ( groupData
.default !== undefined ) {
195 extraValues
.push( String( groupData
.default ) );
197 controller
.addNumberValuesToGroup( groupData
, extraValues
);
202 // Initialize the model
203 this.filtersModel
.initializeFilters( filterStructure
, views
);
205 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
209 if ( !mw
.user
.isAnon() ) {
211 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
213 parsedSavedQueries
= {};
216 // Initialize saved queries
217 this.savedQueriesModel
.initialize( parsedSavedQueries
);
218 if ( this.savedQueriesModel
.isConverted() ) {
219 // Since we know we converted, we're going to re-save
220 // the queries so they are now migrated to the new format
221 this._saveSavedQueries();
225 // Check whether we need to load defaults.
226 // We do this by checking whether the current URI query
227 // contains any parameters recognized by the system.
228 // If it does, we load the given state.
229 // If it doesn't, we have no values at all, and we assume
230 // the user loads the base-page and we load defaults.
231 // Defaults should only be applied on load (if necessary)
233 this.initializing
= true;
235 !mw
.user
.isAnon() && this.savedQueriesModel
.getDefault() &&
236 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
238 // We have defaults from a saved query.
239 // We will load them straight-forward (as if
240 // they were clicked in the menu) so we trigger
241 // a full ajax request and change of URL
242 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
244 // There are either recognized parameters in the URL
245 // or there are none, but there is also no default
246 // saved query (so defaults are from the backend)
247 // We want to update the state but not fetch results
249 this.updateStateFromUrl( false );
251 // Update the changes list with the existing data
252 // so it gets processed
253 this.changesListModel
.update(
254 $changesList
.length
? $changesList
: 'NO_RESULTS',
255 $( 'fieldset.cloptions' ).first(),
256 true // We're using existing DOM elements
260 this.initializing
= false;
261 this.switchView( 'default' );
263 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
264 if ( this.pollingRate
) {
265 this._scheduleLiveUpdate();
270 * Create filter data from a number, for the filters that are numerical value
272 * @param {Number} num Number
273 * @param {Number} numForDisplay Number for the label
274 * @return {Object} Filter data
276 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
279 label
: mw
.language
.convertNumber( numForDisplay
)
284 * Add an arbitrary values to groups that allow arbitrary values
286 * @param {Object} groupData Group data
287 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
289 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
290 var controller
= this,
291 normalizeWithinRange = function ( range
, val
) {
292 if ( val
< range
.min
) {
293 return range
.min
; // Min
294 } else if ( val
>= range
.max
) {
295 return range
.max
; // Max
300 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
302 // Normalize the arbitrary values and the default value for a range
303 if ( groupData
.range
) {
304 arbitraryValues
= arbitraryValues
.map( function ( val
) {
305 return normalizeWithinRange( groupData
.range
, val
);
308 // Normalize the default, since that's user defined
309 if ( groupData
.default !== undefined ) {
310 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
314 // This is only true for single_option group
315 // We assume these are the only groups that will allow for
316 // arbitrary, since it doesn't make any sense for the other
318 arbitraryValues
.forEach( function ( val
) {
320 // If the group allows for arbitrary data
321 groupData
.allowArbitrary
&&
322 // and it is single_option (or string_options, but we
323 // don't have cases of those yet, nor do we plan to)
324 groupData
.type
=== 'single_option' &&
325 // and, if there is a validate method and it passes on
327 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
328 // but if that value isn't already in the definition
330 .map( function ( filterData
) {
331 return String( filterData
.name
);
333 .indexOf( String( val
) ) === -1
335 // Add the filter information
336 groupData
.filters
.push( controller
._createFilterDataFromNumber(
338 groupData
.numToLabelFunc
?
339 groupData
.numToLabelFunc( val
) :
343 // If there's a sort function set up, re-sort the values
344 if ( groupData
.sortFunc
) {
345 groupData
.filters
.sort( groupData
.sortFunc
);
352 * Switch the view of the filters model
354 * @param {string} view Requested view
356 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
357 this.filtersModel
.switchView( view
);
361 * Reset to default filters
363 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
364 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
366 this.updateChangesList();
370 * Check whether the default values of the filters are all false.
372 * @return {boolean} Defaults are all false
374 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
375 var defaultParams
= this._getDefaultParams(),
376 defaultFilters
= this.filtersModel
.getFiltersFromParameters( defaultParams
);
378 this._deleteExcludedValuesFromFilterState( defaultFilters
);
380 if ( Object
.keys( defaultParams
).some( function ( paramName
) {
381 return paramName
.endsWith( '_color' ) && defaultParams
[ paramName
] !== null;
383 // There are highlights in the defaults, they're definitely
388 // Defaults can change in a session, so we need to do this every time
389 return Object
.keys( defaultFilters
).every( function ( filterName
) {
390 return !defaultFilters
[ filterName
];
395 * Empty all selected filters
397 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
398 var highlightedFilterNames
= this.filtersModel
399 .getHighlightedItems()
400 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
402 this.filtersModel
.emptyAllFilters();
403 this.filtersModel
.clearAllHighlightColors();
404 // Check all filter interactions
405 this.filtersModel
.reassessFilterInteractions();
407 this.updateChangesList();
409 if ( highlightedFilterNames
) {
410 this._trackHighlight( 'clearAll', highlightedFilterNames
);
415 * Update the selected state of a filter
417 * @param {string} filterName Filter name
418 * @param {boolean} [isSelected] Filter selected state
420 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
421 var filterItem
= this.filtersModel
.getItemByName( filterName
);
424 // If no filter was found, break
428 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
430 if ( filterItem
.isSelected() !== isSelected
) {
431 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
433 this.updateChangesList();
435 // Check filter interactions
436 this.filtersModel
.reassessFilterInteractions( filterItem
);
441 * Clear both highlight and selection of a filter
443 * @param {string} filterName Name of the filter item
445 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
446 var filterItem
= this.filtersModel
.getItemByName( filterName
),
447 isHighlighted
= filterItem
.isHighlighted();
449 if ( filterItem
.isSelected() || isHighlighted
) {
450 this.filtersModel
.clearHighlightColor( filterName
);
451 this.filtersModel
.toggleFilterSelected( filterName
, false );
452 this.updateChangesList();
453 this.filtersModel
.reassessFilterInteractions( filterItem
);
455 // Log filter grouping
456 this.trackFilterGroupings( 'removefilter' );
459 if ( isHighlighted
) {
460 this._trackHighlight( 'clear', filterName
);
465 * Toggle the highlight feature on and off
467 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
468 this.filtersModel
.toggleHighlight();
471 if ( this.filtersModel
.isHighlightEnabled() ) {
472 mw
.hook( 'RcFilters.highlight.enable' ).fire();
477 * Toggle the namespaces inverted feature on and off
479 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
480 this.filtersModel
.toggleInvertedNamespaces();
483 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
484 function ( filterItem
) { return filterItem
.isSelected(); }
487 // Only re-fetch results if there are namespace items that are actually selected
488 this.updateChangesList();
493 * Set the highlight color for a filter item
495 * @param {string} filterName Name of the filter item
496 * @param {string} color Selected color
498 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
499 this.filtersModel
.setHighlightColor( filterName
, color
);
501 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
505 * Clear highlight for a filter item
507 * @param {string} filterName Name of the filter item
509 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
510 this.filtersModel
.clearHighlightColor( filterName
);
512 this._trackHighlight( 'clear', filterName
);
516 * Enable or disable live updates.
517 * @param {boolean} enable True to enable, false to disable
519 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
520 this.changesListModel
.toggleLiveUpdate( enable
);
521 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
522 this.updateChangesList( null, this.LIVE_UPDATE
);
527 * Set a timeout for the next live update.
530 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
531 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
535 * Perform a live update.
538 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
539 if ( !this._shouldCheckForNewChanges() ) {
540 // skip this turn and check back later
541 this._scheduleLiveUpdate();
545 this._checkForNewChanges()
546 .then( function ( newChanges
) {
547 if ( !this._shouldCheckForNewChanges() ) {
548 // by the time the response is received,
549 // it may not be appropriate anymore
554 if ( this.changesListModel
.getLiveUpdate() ) {
555 return this.updateChangesList( null, this.LIVE_UPDATE
);
557 this.changesListModel
.setNewChangesExist( true );
561 .always( this._scheduleLiveUpdate
.bind( this ) );
565 * @return {boolean} It's appropriate to check for new changes now
568 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
569 return !document
.hidden
&&
570 !this.filtersModel
.hasConflict() &&
571 !this.changesListModel
.getNewChangesExist() &&
572 !this.updatingChangesList
&&
573 this.changesListModel
.getNextFrom();
577 * Check if new changes, newer than those currently shown, are available
579 * @return {jQuery.Promise} Promise object that resolves with a bool
580 * specifying if there are new changes or not
584 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
587 peek
: 1, // bypasses ChangesList specific UI
588 from: this.changesListModel
.getNextFrom()
590 return this._queryChangesList( 'liveUpdate', params
).then(
592 // no result is 204 with the 'peek' param
593 return data
.status
=== 200;
599 * Show the new changes
601 * @return {jQuery.Promise} Promise object that resolves after
602 * fetching and showing the new changes
604 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
605 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
609 * Save the current model state as a saved query
611 * @param {string} [label] Label of the saved query
612 * @param {boolean} [setAsDefault=false] This query should be set as the default
614 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
615 var highlightedItems
= {},
616 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
617 selectedState
= this.filtersModel
.getSelectedState();
619 // Prepare highlights
620 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
621 highlightedItems
[ item
.getName() + '_color' ] = highlightEnabled
?
622 item
.getHighlightColor() : null;
625 // Delete all excluded filters
626 this._deleteExcludedValuesFromFilterState( selectedState
);
629 this.savedQueriesModel
.addNewQuery(
630 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
635 invert
: String( Number( this.filtersModel
.areNamespacesInverted() ) ),
636 highlight
: String( Number( this.filtersModel
.isHighlightEnabled() ) )
638 this.filtersModel
.getParametersFromFilters( selectedState
)
640 highlights
: highlightedItems
646 this._saveSavedQueries();
650 * Remove a saved query
652 * @param {string} queryID Query id
654 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
655 this.savedQueriesModel
.removeQuery( queryID
);
657 this._saveSavedQueries();
661 * Rename a saved query
663 * @param {string} queryID Query id
664 * @param {string} newLabel New label for the query
666 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
667 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
670 queryItem
.updateLabel( newLabel
);
672 this._saveSavedQueries();
676 * Set a saved query as default
678 * @param {string} queryID Query Id. If null is given, default
681 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
682 this.savedQueriesModel
.setDefault( queryID
);
683 this._saveSavedQueries();
689 * @param {string} queryID Query id
691 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
693 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
694 data
= this.savedQueriesModel
.getItemFullData( queryID
),
695 currentMatchingQuery
= this.findQueryMatchingCurrentState();
700 // If there's already a query, don't reload it
701 // if it's the same as the one that already exists
702 !currentMatchingQuery
||
703 currentMatchingQuery
.getID() !== queryItem
.getID()
706 highlights
= data
.highlights
;
708 // Update model state from filters
709 this.filtersModel
.toggleFiltersSelected(
710 // Merge filters with excluded values
714 this.filtersModel
.getFiltersFromParameters( data
.params
),
715 this.filtersModel
.getExcludedFiltersState()
719 // Update namespace inverted property
720 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.params
.invert
) );
722 // Update highlight state
723 this.filtersModel
.toggleHighlight( !!Number( data
.params
.highlight
) );
724 this.filtersModel
.getItems().forEach( function ( filterItem
) {
725 var color
= highlights
[ filterItem
.getName() + '_color' ];
727 filterItem
.setHighlightColor( color
);
729 filterItem
.clearHighlightColor();
733 // Check all filter interactions
734 this.filtersModel
.reassessFilterInteractions();
736 this.updateChangesList();
738 // Log filter grouping
739 this.trackFilterGroupings( 'savedfilters' );
744 * Check whether the current filter and highlight state exists
745 * in the saved queries model.
747 * @return {boolean} Query exists
749 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
750 var highlightedItems
= {},
751 selectedState
= this.filtersModel
.getSelectedState();
753 // Prepare highlights of the current query
754 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
755 highlightedItems
[ item
.getName() + '_color' ] = item
.getHighlightColor();
758 // Remove anything that should be excluded from the saved query
759 // this includes sticky filters and filters marked with 'excludedFromSavedQueries'
760 this._deleteExcludedValuesFromFilterState( selectedState
);
762 return this.savedQueriesModel
.findMatchingQuery(
767 highlight
: String( Number( this.filtersModel
.isHighlightEnabled() ) ),
768 invert
: String( Number( this.filtersModel
.areNamespacesInverted() ) )
770 this.filtersModel
.getParametersFromFilters( selectedState
)
772 highlights
: highlightedItems
778 * Delete sticky filters from given object
780 * @param {Object} filterState Filter state
782 mw
.rcfilters
.Controller
.prototype._deleteExcludedValuesFromFilterState = function ( filterState
) {
783 // Remove excluded filters
784 $.each( this.filtersModel
.getExcludedFiltersState(), function ( filterName
) {
785 delete filterState
[ filterName
];
790 * Save the current state of the saved queries model with all
791 * query item representation in the user settings.
793 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
794 var stringified
, oldPrefValue
,
795 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
796 state
= this.savedQueriesModel
.getState();
799 stringified
= JSON
.stringify( state
);
801 if ( $.byteLength( stringified
) > 65535 ) {
802 // Sanity check, since the preference can only hold that.
806 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
807 // The queries were converted from the previous version
808 // Keep the old string in the [prefname]-versionbackup
809 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
811 // Save the old preference in the backup preference
812 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
813 // Update the preference for this session
814 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
817 // Save the preference
818 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
819 // Update the preference for this session
820 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
822 // Tag as already saved so we don't do this again
823 this.wereSavedQueriesSaved
= true;
827 * Update sticky preferences with current model state
829 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
830 // Update default sticky values with selected, whether they came from
831 // the initial defaults or from the URL value that is being normalized
832 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
833 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
835 // TODO: Make these automatic by having the model go over sticky
836 // items and update their default values automatically
840 * Update the limit default value
842 * param {number} newValue New value
844 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
845 // HACK: Temporarily remove this from being sticky
849 if ( !$.isNumeric( newValue ) ) {
853 newValue = Number( newValue );
855 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
856 // Save the preference
857 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
858 // Update the preference for this session
859 mw.user.options.set( 'rcfilters-rclimit', newValue );
866 * Update the days default value
868 * param {number} newValue New value
870 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
871 // HACK: Temporarily remove this from being sticky
875 if ( !$.isNumeric( newValue ) ) {
879 newValue = Number( newValue );
881 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
882 // Save the preference
883 new mw.Api().saveOption( 'rcdays', newValue );
884 // Update the preference for this session
885 mw.user.options.set( 'rcdays', newValue );
892 * Update the group by page default value
894 * @param {number} newValue New value
896 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
897 if ( !$.isNumeric( newValue
) ) {
901 newValue
= Number( newValue
);
903 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
904 // Save the preference
905 new mw
.Api().saveOption( 'usenewrc', newValue
);
906 // Update the preference for this session
907 mw
.user
.options
.set( 'usenewrc', newValue
);
912 * Synchronize the URL with the current state of the filters
913 * without adding an history entry.
915 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
916 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
920 * Update filter state (selection and highlighting) based
921 * on current URL values.
923 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
924 * list based on the updated model.
926 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
927 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
929 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
931 // Update the sticky preferences, in case we received a value
933 this.updateStickyPreferences();
935 // Only update and fetch new results if it is requested
936 if ( fetchChangesList
) {
937 this.updateChangesList();
942 * Update the list of changes and notify the model
944 * @param {Object} [params] Extra parameters to add to the API call
945 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
946 * @return {jQuery.Promise} Promise that is resolved when the update is complete
948 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
949 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
951 if ( updateMode
=== this.FILTER_CHANGE
) {
952 this._updateURL( params
);
954 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
955 this.changesListModel
.invalidate();
957 this.changesListModel
.setNewChangesExist( false );
958 this.updatingChangesList
= true;
959 return this._fetchChangesList()
962 function ( pieces
) {
963 var $changesListContent
= pieces
.changes
,
964 $fieldset
= pieces
.fieldset
;
965 this.changesListModel
.update(
969 // separator between old and new changes
970 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
973 // Do nothing for failure
975 .always( function () {
976 this.updatingChangesList
= false;
981 * Get an object representing the default parameter state, whether
982 * it is from the model defaults or from the saved queries.
984 * @return {Object} Default parameters
986 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
988 data
= ( !mw
.user
.isAnon() && this.savedQueriesModel
.getItemFullData( this.savedQueriesModel
.getDefault() ) ) || {};
990 if ( !$.isEmptyObject( data
) ) {
991 // Merge saved filter state with sticky filter values
992 savedFilters
= $.extend(
994 this.filtersModel
.getFiltersFromParameters( data
.params
),
995 this.filtersModel
.getStickyFiltersState()
998 // Return parameter representation
999 return $.extend( true, {},
1000 this.filtersModel
.getParametersFromFilters( savedFilters
),
1002 { highlight
: data
.params
.highlight
, invert
: data
.params
.invert
}
1005 return this.filtersModel
.getDefaultParams();
1009 * Update the URL of the page to reflect current filters
1011 * This should not be called directly from outside the controller.
1012 * If an action requires changing the URL, it should either use the
1013 * highlighting actions below, or call #updateChangesList which does
1014 * the uri corrections already.
1016 * @param {Object} [params] Extra parameters to add to the API call
1018 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1019 var currentUri
= new mw
.Uri(),
1020 updatedUri
= this._getUpdatedUri();
1022 updatedUri
.extend( params
|| {} );
1025 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1026 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1028 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1033 * Get an updated mw.Uri object based on the model state
1035 * @return {mw.Uri} Updated Uri
1037 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1038 var uri
= new mw
.Uri();
1041 uri
.query
= this.uriProcessor
.minimizeQuery(
1045 // We want to retain unrecognized params
1046 // The uri params from model will override
1047 // any recognized value in the current uri
1048 // query, retain unrecognized params, and
1049 // the result will then be minimized
1051 this.uriProcessor
.getUriParametersFromModel(),
1060 * Query the list of changes from the server for the current filters
1062 * @param {string} counterId Id for this request. To allow concurrent requests
1063 * not to invalidate each other.
1064 * @param {Object} [params={}] Parameters to add to the query
1066 * @return {jQuery.Promise} Promise object resolved with { content, status }
1068 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1069 var uri
= this._getUpdatedUri(),
1070 stickyParams
= this.filtersModel
.getStickyParams(),
1074 params
= params
|| {};
1075 params
.action
= 'render'; // bypasses MW chrome
1077 uri
.extend( params
);
1079 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1080 requestId
= ++this.requestCounter
[ counterId
];
1081 latestRequest = function () {
1082 return requestId
=== this.requestCounter
[ counterId
];
1085 // Sticky parameters override the URL params
1086 // this is to make sure that whether we represent
1087 // the sticky params in the URL or not (they may
1088 // be normalized out) the sticky parameters are
1089 // always being sent to the server with their
1090 // current/default values
1091 uri
.extend( stickyParams
);
1093 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1095 function ( content
, message
, jqXHR
) {
1096 if ( !latestRequest() ) {
1097 return $.Deferred().reject();
1101 status
: jqXHR
.status
1104 // RC returns 404 when there is no results
1105 function ( jqXHR
) {
1106 if ( latestRequest() ) {
1107 return $.Deferred().resolve(
1109 content
: jqXHR
.responseText
,
1110 status
: jqXHR
.status
1119 * Fetch the list of changes from the server for the current filters
1121 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1124 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1125 return this._queryChangesList( 'updateChangesList' )
1128 var $parsed
= $( '<div>' ).append( $( $.parseHTML( data
.content
) ) ),
1131 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1133 fieldset
: $parsed
.find( 'fieldset.cloptions' ).first()
1136 if ( pieces
.changes
.length
=== 0 ) {
1137 pieces
.changes
= 'NO_RESULTS';
1146 * Track usage of highlight feature
1148 * @param {string} action
1149 * @param {Array|Object|string} filters
1151 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1152 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1153 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1155 'event.ChangesListHighlights',
1159 userId
: mw
.user
.getId()
1165 * Track filter grouping usage
1167 * @param {string} action Action taken
1169 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1170 var controller
= this,
1171 rightNow
= new Date().getTime(),
1172 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1173 // Get all current filters
1174 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1175 return item
.getName();
1178 action
= action
|| 'filtermenu';
1180 // Check if these filters were the ones we just logged previously
1181 // (Don't log the same grouping twice, in case the user opens/closes)
1182 // the menu without action, or with the same result
1184 // Only log if the two arrays are different in size
1185 filters
.length
!== this.prevLoggedItems
.length
||
1186 // Or if any filters are not the same as the cached filters
1187 filters
.some( function ( filterName
) {
1188 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1190 // Or if any cached filters are not the same as given filters
1191 this.prevLoggedItems
.some( function ( filterName
) {
1192 return filters
.indexOf( filterName
) === -1;
1195 filters
.forEach( function ( filterName
) {
1197 'event.ChangesListFilterGrouping',
1200 groupIdentifier
: randomIdentifier
,
1202 userId
: mw
.user
.getId()
1207 // Cache the filter names
1208 this.prevLoggedItems
= filters
;
1213 * Mark all changes as seen on Watchlist
1215 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1216 var api
= new mw
.Api();
1217 api
.postWithToken( 'csrf', {
1219 action
: 'setnotificationtimestamp',
1220 entirewatchlist
: true
1221 } ).then( function () {
1222 this.updateChangesList( null, 'markSeen' );
1225 }( mediaWiki
, jQuery
) );