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
, pieces
,
45 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
46 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
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 if ( defaultSavedQueryExists
) {
236 // This came from the server, meaning that we have a default
237 // saved query, but the server could not load it, probably because
238 // it was pre-conversion to the new format.
239 // We need to load this query again
240 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
242 // There are either recognized parameters in the URL
243 // or there are none, but there is also no default
244 // saved query (so defaults are from the backend)
245 // We want to update the state but not fetch results
247 this.updateStateFromUrl( false );
249 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
251 // Update the changes list with the existing data
252 // so it gets processed
253 this.changesListModel
.update(
256 pieces
.noResultsDetails
=== 'NO_RESULTS_TIMEOUT',
257 true // We're using existing DOM elements
261 this.initializing
= false;
262 this.switchView( 'default' );
264 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
265 if ( this.pollingRate
) {
266 this._scheduleLiveUpdate();
271 * Extracts information from the changes list DOM
273 * @param {jQuery} $root Root DOM to find children from
274 * @return {Object} Information about changes list
275 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
276 * (either normally or as an error)
277 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
278 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
279 * @return {jQuery} return.fieldset Fieldset
281 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
) {
283 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
284 areResults
= !!$changesListContents
.length
;
287 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
288 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
292 isTimeout
= !!$root
.find( '.mw-changeslist-timeout' ).length
;
293 info
.noResultsDetails
= isTimeout
? 'NO_RESULTS_TIMEOUT' : 'NO_RESULTS_NORMAL';
300 * Create filter data from a number, for the filters that are numerical value
302 * @param {Number} num Number
303 * @param {Number} numForDisplay Number for the label
304 * @return {Object} Filter data
306 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
309 label
: mw
.language
.convertNumber( numForDisplay
)
314 * Add an arbitrary values to groups that allow arbitrary values
316 * @param {Object} groupData Group data
317 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
319 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
320 var controller
= this,
321 normalizeWithinRange = function ( range
, val
) {
322 if ( val
< range
.min
) {
323 return range
.min
; // Min
324 } else if ( val
>= range
.max
) {
325 return range
.max
; // Max
330 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
332 // Normalize the arbitrary values and the default value for a range
333 if ( groupData
.range
) {
334 arbitraryValues
= arbitraryValues
.map( function ( val
) {
335 return normalizeWithinRange( groupData
.range
, val
);
338 // Normalize the default, since that's user defined
339 if ( groupData
.default !== undefined ) {
340 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
344 // This is only true for single_option group
345 // We assume these are the only groups that will allow for
346 // arbitrary, since it doesn't make any sense for the other
348 arbitraryValues
.forEach( function ( val
) {
350 // If the group allows for arbitrary data
351 groupData
.allowArbitrary
&&
352 // and it is single_option (or string_options, but we
353 // don't have cases of those yet, nor do we plan to)
354 groupData
.type
=== 'single_option' &&
355 // and, if there is a validate method and it passes on
357 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
358 // but if that value isn't already in the definition
360 .map( function ( filterData
) {
361 return String( filterData
.name
);
363 .indexOf( String( val
) ) === -1
365 // Add the filter information
366 groupData
.filters
.push( controller
._createFilterDataFromNumber(
368 groupData
.numToLabelFunc
?
369 groupData
.numToLabelFunc( val
) :
373 // If there's a sort function set up, re-sort the values
374 if ( groupData
.sortFunc
) {
375 groupData
.filters
.sort( groupData
.sortFunc
);
382 * Switch the view of the filters model
384 * @param {string} view Requested view
386 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
387 this.filtersModel
.switchView( view
);
391 * Reset to default filters
393 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
394 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
396 this.updateChangesList();
400 * Check whether the default values of the filters are all false.
402 * @return {boolean} Defaults are all false
404 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
405 var defaultParams
= this._getDefaultParams(),
406 defaultFilters
= this.filtersModel
.getFiltersFromParameters( defaultParams
);
408 this._deleteExcludedValuesFromFilterState( defaultFilters
);
410 if ( Object
.keys( defaultParams
).some( function ( paramName
) {
411 return paramName
.endsWith( '_color' ) && defaultParams
[ paramName
] !== null;
413 // There are highlights in the defaults, they're definitely
418 // Defaults can change in a session, so we need to do this every time
419 return Object
.keys( defaultFilters
).every( function ( filterName
) {
420 return !defaultFilters
[ filterName
];
425 * Empty all selected filters
427 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
428 var highlightedFilterNames
= this.filtersModel
429 .getHighlightedItems()
430 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
432 this.filtersModel
.emptyAllFilters();
433 this.filtersModel
.clearAllHighlightColors();
434 // Check all filter interactions
435 this.filtersModel
.reassessFilterInteractions();
437 this.updateChangesList();
439 if ( highlightedFilterNames
) {
440 this._trackHighlight( 'clearAll', highlightedFilterNames
);
445 * Update the selected state of a filter
447 * @param {string} filterName Filter name
448 * @param {boolean} [isSelected] Filter selected state
450 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
451 var filterItem
= this.filtersModel
.getItemByName( filterName
);
454 // If no filter was found, break
458 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
460 if ( filterItem
.isSelected() !== isSelected
) {
461 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
463 this.updateChangesList();
465 // Check filter interactions
466 this.filtersModel
.reassessFilterInteractions( filterItem
);
471 * Clear both highlight and selection of a filter
473 * @param {string} filterName Name of the filter item
475 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
476 var filterItem
= this.filtersModel
.getItemByName( filterName
),
477 isHighlighted
= filterItem
.isHighlighted();
479 if ( filterItem
.isSelected() || isHighlighted
) {
480 this.filtersModel
.clearHighlightColor( filterName
);
481 this.filtersModel
.toggleFilterSelected( filterName
, false );
482 this.updateChangesList();
483 this.filtersModel
.reassessFilterInteractions( filterItem
);
485 // Log filter grouping
486 this.trackFilterGroupings( 'removefilter' );
489 if ( isHighlighted
) {
490 this._trackHighlight( 'clear', filterName
);
495 * Toggle the highlight feature on and off
497 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
498 this.filtersModel
.toggleHighlight();
501 if ( this.filtersModel
.isHighlightEnabled() ) {
502 mw
.hook( 'RcFilters.highlight.enable' ).fire();
507 * Toggle the namespaces inverted feature on and off
509 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
510 this.filtersModel
.toggleInvertedNamespaces();
513 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
514 function ( filterItem
) { return filterItem
.isSelected(); }
517 // Only re-fetch results if there are namespace items that are actually selected
518 this.updateChangesList();
523 * Set the highlight color for a filter item
525 * @param {string} filterName Name of the filter item
526 * @param {string} color Selected color
528 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
529 this.filtersModel
.setHighlightColor( filterName
, color
);
531 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
535 * Clear highlight for a filter item
537 * @param {string} filterName Name of the filter item
539 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
540 this.filtersModel
.clearHighlightColor( filterName
);
542 this._trackHighlight( 'clear', filterName
);
546 * Enable or disable live updates.
547 * @param {boolean} enable True to enable, false to disable
549 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
550 this.changesListModel
.toggleLiveUpdate( enable
);
551 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
552 this.updateChangesList( null, this.LIVE_UPDATE
);
557 * Set a timeout for the next live update.
560 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
561 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
565 * Perform a live update.
568 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
569 if ( !this._shouldCheckForNewChanges() ) {
570 // skip this turn and check back later
571 this._scheduleLiveUpdate();
575 this._checkForNewChanges()
576 .then( function ( newChanges
) {
577 if ( !this._shouldCheckForNewChanges() ) {
578 // by the time the response is received,
579 // it may not be appropriate anymore
584 if ( this.changesListModel
.getLiveUpdate() ) {
585 return this.updateChangesList( null, this.LIVE_UPDATE
);
587 this.changesListModel
.setNewChangesExist( true );
591 .always( this._scheduleLiveUpdate
.bind( this ) );
595 * @return {boolean} It's appropriate to check for new changes now
598 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
599 return !document
.hidden
&&
600 !this.filtersModel
.hasConflict() &&
601 !this.changesListModel
.getNewChangesExist() &&
602 !this.updatingChangesList
&&
603 this.changesListModel
.getNextFrom();
607 * Check if new changes, newer than those currently shown, are available
609 * @return {jQuery.Promise} Promise object that resolves with a bool
610 * specifying if there are new changes or not
614 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
617 peek
: 1, // bypasses ChangesList specific UI
618 from: this.changesListModel
.getNextFrom()
620 return this._queryChangesList( 'liveUpdate', params
).then(
622 // no result is 204 with the 'peek' param
623 return data
.status
=== 200;
629 * Show the new changes
631 * @return {jQuery.Promise} Promise object that resolves after
632 * fetching and showing the new changes
634 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
635 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
639 * Save the current model state as a saved query
641 * @param {string} [label] Label of the saved query
642 * @param {boolean} [setAsDefault=false] This query should be set as the default
644 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
645 var highlightedItems
= {},
646 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
647 selectedState
= this.filtersModel
.getSelectedState();
649 // Prepare highlights
650 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
651 highlightedItems
[ item
.getName() + '_color' ] = highlightEnabled
?
652 item
.getHighlightColor() : null;
655 // Delete all excluded filters
656 this._deleteExcludedValuesFromFilterState( selectedState
);
659 this.savedQueriesModel
.addNewQuery(
660 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
665 invert
: String( Number( this.filtersModel
.areNamespacesInverted() ) ),
666 highlight
: String( Number( this.filtersModel
.isHighlightEnabled() ) )
668 this.filtersModel
.getParametersFromFilters( selectedState
)
670 highlights
: highlightedItems
676 this._saveSavedQueries();
680 * Remove a saved query
682 * @param {string} queryID Query id
684 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
685 this.savedQueriesModel
.removeQuery( queryID
);
687 this._saveSavedQueries();
691 * Rename a saved query
693 * @param {string} queryID Query id
694 * @param {string} newLabel New label for the query
696 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
697 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
700 queryItem
.updateLabel( newLabel
);
702 this._saveSavedQueries();
706 * Set a saved query as default
708 * @param {string} queryID Query Id. If null is given, default
711 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
712 this.savedQueriesModel
.setDefault( queryID
);
713 this._saveSavedQueries();
719 * @param {string} queryID Query id
721 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
723 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
724 data
= this.savedQueriesModel
.getItemFullData( queryID
),
725 currentMatchingQuery
= this.findQueryMatchingCurrentState();
730 // If there's already a query, don't reload it
731 // if it's the same as the one that already exists
732 !currentMatchingQuery
||
733 currentMatchingQuery
.getID() !== queryItem
.getID()
736 highlights
= data
.highlights
;
738 // Update model state from filters
739 this.filtersModel
.toggleFiltersSelected(
740 // Merge filters with excluded values
744 this.filtersModel
.getFiltersFromParameters( data
.params
),
745 this.filtersModel
.getExcludedFiltersState()
749 // Update namespace inverted property
750 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.params
.invert
) );
752 // Update highlight state
753 this.filtersModel
.toggleHighlight( !!Number( data
.params
.highlight
) );
754 this.filtersModel
.getItems().forEach( function ( filterItem
) {
755 var color
= highlights
[ filterItem
.getName() + '_color' ];
757 filterItem
.setHighlightColor( color
);
759 filterItem
.clearHighlightColor();
763 // Check all filter interactions
764 this.filtersModel
.reassessFilterInteractions();
766 this.updateChangesList();
768 // Log filter grouping
769 this.trackFilterGroupings( 'savedfilters' );
774 * Check whether the current filter and highlight state exists
775 * in the saved queries model.
777 * @return {boolean} Query exists
779 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
780 var highlightedItems
= {},
781 selectedState
= this.filtersModel
.getSelectedState();
783 // Prepare highlights of the current query
784 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
785 highlightedItems
[ item
.getName() + '_color' ] = item
.getHighlightColor();
788 // Remove anything that should be excluded from the saved query
789 // this includes sticky filters and filters marked with 'excludedFromSavedQueries'
790 this._deleteExcludedValuesFromFilterState( selectedState
);
792 return this.savedQueriesModel
.findMatchingQuery(
797 highlight
: String( Number( this.filtersModel
.isHighlightEnabled() ) ),
798 invert
: String( Number( this.filtersModel
.areNamespacesInverted() ) )
800 this.filtersModel
.getParametersFromFilters( selectedState
)
802 highlights
: highlightedItems
808 * Delete sticky filters from given object
810 * @param {Object} filterState Filter state
812 mw
.rcfilters
.Controller
.prototype._deleteExcludedValuesFromFilterState = function ( filterState
) {
813 // Remove excluded filters
814 $.each( this.filtersModel
.getExcludedFiltersState(), function ( filterName
) {
815 delete filterState
[ filterName
];
820 * Save the current state of the saved queries model with all
821 * query item representation in the user settings.
823 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
824 var stringified
, oldPrefValue
,
825 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
826 state
= this.savedQueriesModel
.getState();
829 stringified
= JSON
.stringify( state
);
831 if ( $.byteLength( stringified
) > 65535 ) {
832 // Sanity check, since the preference can only hold that.
836 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
837 // The queries were converted from the previous version
838 // Keep the old string in the [prefname]-versionbackup
839 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
841 // Save the old preference in the backup preference
842 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
843 // Update the preference for this session
844 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
847 // Save the preference
848 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
849 // Update the preference for this session
850 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
852 // Tag as already saved so we don't do this again
853 this.wereSavedQueriesSaved
= true;
857 * Update sticky preferences with current model state
859 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
860 // Update default sticky values with selected, whether they came from
861 // the initial defaults or from the URL value that is being normalized
862 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
863 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
865 // TODO: Make these automatic by having the model go over sticky
866 // items and update their default values automatically
870 * Update the limit default value
872 * param {number} newValue New value
874 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
875 // HACK: Temporarily remove this from being sticky
879 if ( !$.isNumeric( newValue ) ) {
883 newValue = Number( newValue );
885 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
886 // Save the preference
887 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
888 // Update the preference for this session
889 mw.user.options.set( 'rcfilters-rclimit', newValue );
896 * Update the days default value
898 * param {number} newValue New value
900 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
901 // HACK: Temporarily remove this from being sticky
905 if ( !$.isNumeric( newValue ) ) {
909 newValue = Number( newValue );
911 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
912 // Save the preference
913 new mw.Api().saveOption( 'rcdays', newValue );
914 // Update the preference for this session
915 mw.user.options.set( 'rcdays', newValue );
922 * Update the group by page default value
924 * @param {number} newValue New value
926 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
927 if ( !$.isNumeric( newValue
) ) {
931 newValue
= Number( newValue
);
933 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
934 // Save the preference
935 new mw
.Api().saveOption( 'usenewrc', newValue
);
936 // Update the preference for this session
937 mw
.user
.options
.set( 'usenewrc', newValue
);
942 * Synchronize the URL with the current state of the filters
943 * without adding an history entry.
945 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
946 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
950 * Update filter state (selection and highlighting) based
951 * on current URL values.
953 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
954 * list based on the updated model.
956 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
957 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
959 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
961 // Update the sticky preferences, in case we received a value
963 this.updateStickyPreferences();
965 // Only update and fetch new results if it is requested
966 if ( fetchChangesList
) {
967 this.updateChangesList();
972 * Update the list of changes and notify the model
974 * @param {Object} [params] Extra parameters to add to the API call
975 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
976 * @return {jQuery.Promise} Promise that is resolved when the update is complete
978 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
979 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
981 if ( updateMode
=== this.FILTER_CHANGE
) {
982 this._updateURL( params
);
984 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
985 this.changesListModel
.invalidate();
987 this.changesListModel
.setNewChangesExist( false );
988 this.updatingChangesList
= true;
989 return this._fetchChangesList()
992 function ( pieces
) {
993 var $changesListContent
= pieces
.changes
,
994 $fieldset
= pieces
.fieldset
;
995 this.changesListModel
.update(
998 pieces
.noResultsDetails
=== 'NO_RESULTS_TIMEOUT',
1000 // separator between old and new changes
1001 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
1004 // Do nothing for failure
1006 .always( function () {
1007 this.updatingChangesList
= false;
1012 * Get an object representing the default parameter state, whether
1013 * it is from the model defaults or from the saved queries.
1015 * @return {Object} Default parameters
1017 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
1019 data
= ( !mw
.user
.isAnon() && this.savedQueriesModel
.getItemFullData( this.savedQueriesModel
.getDefault() ) ) || {};
1021 if ( !$.isEmptyObject( data
) ) {
1022 // Merge saved filter state with sticky filter values
1023 savedFilters
= $.extend(
1025 this.filtersModel
.getFiltersFromParameters( data
.params
),
1026 this.filtersModel
.getStickyFiltersState()
1029 // Return parameter representation
1030 return $.extend( true, {},
1031 this.filtersModel
.getParametersFromFilters( savedFilters
),
1033 { highlight
: data
.params
.highlight
, invert
: data
.params
.invert
}
1036 return this.filtersModel
.getDefaultParams();
1040 * Update the URL of the page to reflect current filters
1042 * This should not be called directly from outside the controller.
1043 * If an action requires changing the URL, it should either use the
1044 * highlighting actions below, or call #updateChangesList which does
1045 * the uri corrections already.
1047 * @param {Object} [params] Extra parameters to add to the API call
1049 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1050 var currentUri
= new mw
.Uri(),
1051 updatedUri
= this._getUpdatedUri();
1053 updatedUri
.extend( params
|| {} );
1056 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1057 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1059 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1064 * Get an updated mw.Uri object based on the model state
1066 * @return {mw.Uri} Updated Uri
1068 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1069 var uri
= new mw
.Uri();
1072 uri
.query
= this.uriProcessor
.minimizeQuery(
1076 // We want to retain unrecognized params
1077 // The uri params from model will override
1078 // any recognized value in the current uri
1079 // query, retain unrecognized params, and
1080 // the result will then be minimized
1082 this.uriProcessor
.getUriParametersFromModel(),
1091 * Query the list of changes from the server for the current filters
1093 * @param {string} counterId Id for this request. To allow concurrent requests
1094 * not to invalidate each other.
1095 * @param {Object} [params={}] Parameters to add to the query
1097 * @return {jQuery.Promise} Promise object resolved with { content, status }
1099 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1100 var uri
= this._getUpdatedUri(),
1101 stickyParams
= this.filtersModel
.getStickyParams(),
1105 params
= params
|| {};
1106 params
.action
= 'render'; // bypasses MW chrome
1108 uri
.extend( params
);
1110 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1111 requestId
= ++this.requestCounter
[ counterId
];
1112 latestRequest = function () {
1113 return requestId
=== this.requestCounter
[ counterId
];
1116 // Sticky parameters override the URL params
1117 // this is to make sure that whether we represent
1118 // the sticky params in the URL or not (they may
1119 // be normalized out) the sticky parameters are
1120 // always being sent to the server with their
1121 // current/default values
1122 uri
.extend( stickyParams
);
1124 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1126 function ( content
, message
, jqXHR
) {
1127 if ( !latestRequest() ) {
1128 return $.Deferred().reject();
1132 status
: jqXHR
.status
1135 // RC returns 404 when there is no results
1136 function ( jqXHR
) {
1137 if ( latestRequest() ) {
1138 return $.Deferred().resolve(
1140 content
: jqXHR
.responseText
,
1141 status
: jqXHR
.status
1150 * Fetch the list of changes from the server for the current filters
1152 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1155 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1156 return this._queryChangesList( 'updateChangesList' )
1159 var $parsed
= $( '<div>' ).append( $( $.parseHTML( data
.content
) ) );
1161 return this._extractChangesListInfo( $parsed
);
1168 * Track usage of highlight feature
1170 * @param {string} action
1171 * @param {Array|Object|string} filters
1173 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1174 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1175 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1177 'event.ChangesListHighlights',
1181 userId
: mw
.user
.getId()
1187 * Track filter grouping usage
1189 * @param {string} action Action taken
1191 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1192 var controller
= this,
1193 rightNow
= new Date().getTime(),
1194 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1195 // Get all current filters
1196 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1197 return item
.getName();
1200 action
= action
|| 'filtermenu';
1202 // Check if these filters were the ones we just logged previously
1203 // (Don't log the same grouping twice, in case the user opens/closes)
1204 // the menu without action, or with the same result
1206 // Only log if the two arrays are different in size
1207 filters
.length
!== this.prevLoggedItems
.length
||
1208 // Or if any filters are not the same as the cached filters
1209 filters
.some( function ( filterName
) {
1210 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1212 // Or if any cached filters are not the same as given filters
1213 this.prevLoggedItems
.some( function ( filterName
) {
1214 return filters
.indexOf( filterName
) === -1;
1217 filters
.forEach( function ( filterName
) {
1219 'event.ChangesListFilterGrouping',
1222 groupIdentifier
: randomIdentifier
,
1224 userId
: mw
.user
.getId()
1229 // Cache the filter names
1230 this.prevLoggedItems
= filters
;
1235 * Mark all changes as seen on Watchlist
1237 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1238 var api
= new mw
.Api();
1239 api
.postWithToken( 'csrf', {
1241 action
: 'setnotificationtimestamp',
1242 entirewatchlist
: true
1243 } ).then( function () {
1244 this.updateChangesList( null, 'markSeen' );
1247 }( mediaWiki
, jQuery
) );