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.uriProcessor
.updateModelBasedOnQuery( 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 var defaultParams
= this._getDefaultParams(),
384 defaultFilters
= this.filtersModel
.getFiltersFromParameters( defaultParams
);
386 this._deleteExcludedValuesFromFilterState( defaultFilters
);
388 if ( Object
.keys( defaultParams
).some( function ( paramName
) {
389 return paramName
.endsWith( '_color' ) && defaultParams
[ paramName
] !== null;
391 // There are highlights in the defaults, they're definitely
396 // Defaults can change in a session, so we need to do this every time
397 return Object
.keys( defaultFilters
).every( function ( filterName
) {
398 return !defaultFilters
[ filterName
];
403 * Empty all selected filters
405 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
406 var highlightedFilterNames
= this.filtersModel
407 .getHighlightedItems()
408 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
410 this.filtersModel
.emptyAllFilters();
411 this.filtersModel
.clearAllHighlightColors();
412 // Check all filter interactions
413 this.filtersModel
.reassessFilterInteractions();
415 this.updateChangesList();
417 if ( highlightedFilterNames
) {
418 this._trackHighlight( 'clearAll', highlightedFilterNames
);
423 * Update the selected state of a filter
425 * @param {string} filterName Filter name
426 * @param {boolean} [isSelected] Filter selected state
428 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
429 var filterItem
= this.filtersModel
.getItemByName( filterName
);
432 // If no filter was found, break
436 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
438 if ( filterItem
.isSelected() !== isSelected
) {
439 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
441 this.updateChangesList();
443 // Check filter interactions
444 this.filtersModel
.reassessFilterInteractions( filterItem
);
449 * Clear both highlight and selection of a filter
451 * @param {string} filterName Name of the filter item
453 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
454 var filterItem
= this.filtersModel
.getItemByName( filterName
),
455 isHighlighted
= filterItem
.isHighlighted(),
456 isSelected
= filterItem
.isSelected();
458 if ( isSelected
|| isHighlighted
) {
459 this.filtersModel
.clearHighlightColor( filterName
);
460 this.filtersModel
.toggleFilterSelected( filterName
, false );
463 // Only update the changes list if the filter changed
464 // its selection state. If it only changed its highlight
466 this.updateChangesList();
469 this.filtersModel
.reassessFilterInteractions( filterItem
);
471 // Log filter grouping
472 this.trackFilterGroupings( 'removefilter' );
475 if ( isHighlighted
) {
476 this._trackHighlight( 'clear', filterName
);
481 * Toggle the highlight feature on and off
483 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
484 this.filtersModel
.toggleHighlight();
487 if ( this.filtersModel
.isHighlightEnabled() ) {
488 mw
.hook( 'RcFilters.highlight.enable' ).fire();
493 * Toggle the namespaces inverted feature on and off
495 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
496 this.filtersModel
.toggleInvertedNamespaces();
499 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
500 function ( filterItem
) { return filterItem
.isSelected(); }
503 // Only re-fetch results if there are namespace items that are actually selected
504 this.updateChangesList();
509 * Set the highlight color for a filter item
511 * @param {string} filterName Name of the filter item
512 * @param {string} color Selected color
514 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
515 this.filtersModel
.setHighlightColor( filterName
, color
);
517 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
521 * Clear highlight for a filter item
523 * @param {string} filterName Name of the filter item
525 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
526 this.filtersModel
.clearHighlightColor( filterName
);
528 this._trackHighlight( 'clear', filterName
);
532 * Enable or disable live updates.
533 * @param {boolean} enable True to enable, false to disable
535 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
536 this.changesListModel
.toggleLiveUpdate( enable
);
537 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
538 this.updateChangesList( null, this.LIVE_UPDATE
);
543 * Set a timeout for the next live update.
546 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
547 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
551 * Perform a live update.
554 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
555 if ( !this._shouldCheckForNewChanges() ) {
556 // skip this turn and check back later
557 this._scheduleLiveUpdate();
561 this._checkForNewChanges()
562 .then( function ( newChanges
) {
563 if ( !this._shouldCheckForNewChanges() ) {
564 // by the time the response is received,
565 // it may not be appropriate anymore
570 if ( this.changesListModel
.getLiveUpdate() ) {
571 return this.updateChangesList( null, this.LIVE_UPDATE
);
573 this.changesListModel
.setNewChangesExist( true );
577 .always( this._scheduleLiveUpdate
.bind( this ) );
581 * @return {boolean} It's appropriate to check for new changes now
584 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
585 return !document
.hidden
&&
586 !this.filtersModel
.hasConflict() &&
587 !this.changesListModel
.getNewChangesExist() &&
588 !this.updatingChangesList
&&
589 this.changesListModel
.getNextFrom();
593 * Check if new changes, newer than those currently shown, are available
595 * @return {jQuery.Promise} Promise object that resolves with a bool
596 * specifying if there are new changes or not
600 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
603 peek
: 1, // bypasses ChangesList specific UI
604 from: this.changesListModel
.getNextFrom()
606 return this._queryChangesList( 'liveUpdate', params
).then(
608 // no result is 204 with the 'peek' param
609 return data
.status
=== 200;
615 * Show the new changes
617 * @return {jQuery.Promise} Promise object that resolves after
618 * fetching and showing the new changes
620 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
621 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
625 * Save the current model state as a saved query
627 * @param {string} [label] Label of the saved query
628 * @param {boolean} [setAsDefault=false] This query should be set as the default
630 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
631 var highlightedItems
= {},
632 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
633 selectedState
= this.filtersModel
.getSelectedState();
635 // Prepare highlights
636 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
637 highlightedItems
[ item
.getName() + '_color' ] = highlightEnabled
?
638 item
.getHighlightColor() : null;
641 // Delete all excluded filters
642 this._deleteExcludedValuesFromFilterState( selectedState
);
645 this.savedQueriesModel
.addNewQuery(
646 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
651 highlight
: String( Number( this.filtersModel
.isHighlightEnabled() ) )
653 this.filtersModel
.getParametersFromFilters( selectedState
)
655 highlights
: highlightedItems
661 this._saveSavedQueries();
665 * Remove a saved query
667 * @param {string} queryID Query id
669 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
670 this.savedQueriesModel
.removeQuery( queryID
);
672 this._saveSavedQueries();
676 * Rename a saved query
678 * @param {string} queryID Query id
679 * @param {string} newLabel New label for the query
681 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
682 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
685 queryItem
.updateLabel( newLabel
);
687 this._saveSavedQueries();
691 * Set a saved query as default
693 * @param {string} queryID Query Id. If null is given, default
696 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
697 this.savedQueriesModel
.setDefault( queryID
);
698 this._saveSavedQueries();
704 * @param {string} queryID Query id
706 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
708 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
709 data
= this.savedQueriesModel
.getItemFullData( queryID
),
710 currentMatchingQuery
= this.findQueryMatchingCurrentState();
715 // If there's already a query, don't reload it
716 // if it's the same as the one that already exists
717 !currentMatchingQuery
||
718 currentMatchingQuery
.getID() !== queryItem
.getID()
721 highlights
= data
.highlights
;
723 // Update model state from filters
724 this.filtersModel
.toggleFiltersSelected(
725 // Merge filters with excluded values
729 this.filtersModel
.getFiltersFromParameters( data
.params
),
730 this.filtersModel
.getExcludedFiltersState()
734 // Update highlight state
735 this.filtersModel
.toggleHighlight( !!Number( data
.params
.highlight
) );
736 this.filtersModel
.getItems().forEach( function ( filterItem
) {
737 var color
= highlights
[ filterItem
.getName() + '_color' ];
739 filterItem
.setHighlightColor( color
);
741 filterItem
.clearHighlightColor();
745 // Check all filter interactions
746 this.filtersModel
.reassessFilterInteractions();
748 this.updateChangesList();
750 // Log filter grouping
751 this.trackFilterGroupings( 'savedfilters' );
756 * Check whether the current filter and highlight state exists
757 * in the saved queries model.
759 * @return {boolean} Query exists
761 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
762 var highlightedItems
= {},
763 selectedState
= this.filtersModel
.getSelectedState();
765 // Prepare highlights of the current query
766 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
767 highlightedItems
[ item
.getName() + '_color' ] = item
.getHighlightColor();
770 // Remove anything that should be excluded from the saved query
771 // this includes sticky filters and filters marked with 'excludedFromSavedQueries'
772 this._deleteExcludedValuesFromFilterState( selectedState
);
774 return this.savedQueriesModel
.findMatchingQuery(
779 highlight
: String( Number( this.filtersModel
.isHighlightEnabled() ) )
781 this.filtersModel
.getParametersFromFilters( selectedState
)
783 highlights
: highlightedItems
789 * Delete sticky filters from given object
791 * @param {Object} filterState Filter state
793 mw
.rcfilters
.Controller
.prototype._deleteExcludedValuesFromFilterState = function ( filterState
) {
794 // Remove excluded filters
795 $.each( this.filtersModel
.getExcludedFiltersState(), function ( filterName
) {
796 delete filterState
[ filterName
];
801 * Save the current state of the saved queries model with all
802 * query item representation in the user settings.
804 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
805 var stringified
, oldPrefValue
,
806 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
807 state
= this.savedQueriesModel
.getState();
810 stringified
= JSON
.stringify( state
);
812 if ( $.byteLength( stringified
) > 65535 ) {
813 // Sanity check, since the preference can only hold that.
817 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
818 // The queries were converted from the previous version
819 // Keep the old string in the [prefname]-versionbackup
820 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
822 // Save the old preference in the backup preference
823 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
824 // Update the preference for this session
825 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
828 // Save the preference
829 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
830 // Update the preference for this session
831 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
833 // Tag as already saved so we don't do this again
834 this.wereSavedQueriesSaved
= true;
838 * Update sticky preferences with current model state
840 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
841 // Update default sticky values with selected, whether they came from
842 // the initial defaults or from the URL value that is being normalized
843 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
844 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
846 // TODO: Make these automatic by having the model go over sticky
847 // items and update their default values automatically
851 * Update the limit default value
853 * param {number} newValue New value
855 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
856 // HACK: Temporarily remove this from being sticky
860 if ( !$.isNumeric( newValue ) ) {
864 newValue = Number( newValue );
866 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
867 // Save the preference
868 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
869 // Update the preference for this session
870 mw.user.options.set( 'rcfilters-rclimit', newValue );
877 * Update the days default value
879 * param {number} newValue New value
881 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
882 // HACK: Temporarily remove this from being sticky
886 if ( !$.isNumeric( newValue ) ) {
890 newValue = Number( newValue );
892 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
893 // Save the preference
894 new mw.Api().saveOption( 'rcdays', newValue );
895 // Update the preference for this session
896 mw.user.options.set( 'rcdays', newValue );
903 * Update the group by page default value
905 * @param {number} newValue New value
907 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
908 if ( !$.isNumeric( newValue
) ) {
912 newValue
= Number( newValue
);
914 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
915 // Save the preference
916 new mw
.Api().saveOption( 'usenewrc', newValue
);
917 // Update the preference for this session
918 mw
.user
.options
.set( 'usenewrc', newValue
);
923 * Synchronize the URL with the current state of the filters
924 * without adding an history entry.
926 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
927 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
931 * Update filter state (selection and highlighting) based
932 * on current URL values.
934 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
935 * list based on the updated model.
937 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
938 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
940 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
942 // Update the sticky preferences, in case we received a value
944 this.updateStickyPreferences();
946 // Only update and fetch new results if it is requested
947 if ( fetchChangesList
) {
948 this.updateChangesList();
953 * Update the list of changes and notify the model
955 * @param {Object} [params] Extra parameters to add to the API call
956 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
957 * @return {jQuery.Promise} Promise that is resolved when the update is complete
959 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
960 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
962 if ( updateMode
=== this.FILTER_CHANGE
) {
963 this._updateURL( params
);
965 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
966 this.changesListModel
.invalidate();
968 this.changesListModel
.setNewChangesExist( false );
969 this.updatingChangesList
= true;
970 return this._fetchChangesList()
973 function ( pieces
) {
974 var $changesListContent
= pieces
.changes
,
975 $fieldset
= pieces
.fieldset
;
976 this.changesListModel
.update(
980 // separator between old and new changes
981 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
984 // Do nothing for failure
986 .always( function () {
987 this.updatingChangesList
= false;
992 * Get an object representing the default parameter state, whether
993 * it is from the model defaults or from the saved queries.
995 * @return {Object} Default parameters
997 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
999 data
= ( !mw
.user
.isAnon() && this.savedQueriesModel
.getItemFullData( this.savedQueriesModel
.getDefault() ) ) || {};
1001 if ( !$.isEmptyObject( data
) ) {
1002 // Merge saved filter state with sticky filter values
1003 savedFilters
= $.extend(
1005 this.filtersModel
.getFiltersFromParameters( data
.params
),
1006 this.filtersModel
.getStickyFiltersState()
1009 // Return parameter representation
1010 return $.extend( true, {},
1011 this.filtersModel
.getParametersFromFilters( savedFilters
),
1013 { highlight
: data
.params
.highlight
}
1016 return this.filtersModel
.getDefaultParams();
1020 * Update the URL of the page to reflect current filters
1022 * This should not be called directly from outside the controller.
1023 * If an action requires changing the URL, it should either use the
1024 * highlighting actions below, or call #updateChangesList which does
1025 * the uri corrections already.
1027 * @param {Object} [params] Extra parameters to add to the API call
1029 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1030 var currentUri
= new mw
.Uri(),
1031 updatedUri
= this._getUpdatedUri();
1033 updatedUri
.extend( params
|| {} );
1036 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1037 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1039 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1044 * Get an updated mw.Uri object based on the model state
1046 * @return {mw.Uri} Updated Uri
1048 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1049 var uri
= new mw
.Uri();
1052 uri
.query
= this.uriProcessor
.minimizeQuery(
1056 // We want to retain unrecognized params
1057 // The uri params from model will override
1058 // any recognized value in the current uri
1059 // query, retain unrecognized params, and
1060 // the result will then be minimized
1062 this.uriProcessor
.getUriParametersFromModel(),
1071 * Query the list of changes from the server for the current filters
1073 * @param {string} counterId Id for this request. To allow concurrent requests
1074 * not to invalidate each other.
1075 * @param {Object} [params={}] Parameters to add to the query
1077 * @return {jQuery.Promise} Promise object resolved with { content, status }
1079 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1080 var uri
= this._getUpdatedUri(),
1081 stickyParams
= this.filtersModel
.getStickyParams(),
1085 params
= params
|| {};
1086 params
.action
= 'render'; // bypasses MW chrome
1088 uri
.extend( params
);
1090 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1091 requestId
= ++this.requestCounter
[ counterId
];
1092 latestRequest = function () {
1093 return requestId
=== this.requestCounter
[ counterId
];
1096 // Sticky parameters override the URL params
1097 // this is to make sure that whether we represent
1098 // the sticky params in the URL or not (they may
1099 // be normalized out) the sticky parameters are
1100 // always being sent to the server with their
1101 // current/default values
1102 uri
.extend( stickyParams
);
1104 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1106 function ( content
, message
, jqXHR
) {
1107 if ( !latestRequest() ) {
1108 return $.Deferred().reject();
1112 status
: jqXHR
.status
1115 // RC returns 404 when there is no results
1116 function ( jqXHR
) {
1117 if ( latestRequest() ) {
1118 return $.Deferred().resolve(
1120 content
: jqXHR
.responseText
,
1121 status
: jqXHR
.status
1130 * Fetch the list of changes from the server for the current filters
1132 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1135 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1136 return this._queryChangesList( 'updateChangesList' )
1139 var $parsed
= $( '<div>' ).append( $( $.parseHTML( data
.content
) ) ),
1142 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1144 fieldset
: $parsed
.find( 'fieldset.cloptions' ).first()
1147 if ( pieces
.changes
.length
=== 0 ) {
1148 pieces
.changes
= 'NO_RESULTS';
1157 * Track usage of highlight feature
1159 * @param {string} action
1160 * @param {Array|Object|string} filters
1162 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1163 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1164 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1166 'event.ChangesListHighlights',
1170 userId
: mw
.user
.getId()
1176 * Track filter grouping usage
1178 * @param {string} action Action taken
1180 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1181 var controller
= this,
1182 rightNow
= new Date().getTime(),
1183 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1184 // Get all current filters
1185 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1186 return item
.getName();
1189 action
= action
|| 'filtermenu';
1191 // Check if these filters were the ones we just logged previously
1192 // (Don't log the same grouping twice, in case the user opens/closes)
1193 // the menu without action, or with the same result
1195 // Only log if the two arrays are different in size
1196 filters
.length
!== this.prevLoggedItems
.length
||
1197 // Or if any filters are not the same as the cached filters
1198 filters
.some( function ( filterName
) {
1199 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1201 // Or if any cached filters are not the same as given filters
1202 this.prevLoggedItems
.some( function ( filterName
) {
1203 return filters
.indexOf( filterName
) === -1;
1206 filters
.forEach( function ( filterName
) {
1208 'event.ChangesListFilterGrouping',
1211 groupIdentifier
: randomIdentifier
,
1213 userId
: mw
.user
.getId()
1218 // Cache the filter names
1219 this.prevLoggedItems
= filters
;
1224 * Mark all changes as seen on Watchlist
1226 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1227 var api
= new mw
.Api();
1228 api
.postWithToken( 'csrf', {
1230 action
: 'setnotificationtimestamp',
1231 entirewatchlist
: true
1232 } ).then( function () {
1233 this.updateChangesList( null, 'markSeen' );
1236 }( mediaWiki
, jQuery
) );