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
12 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
) {
13 this.filtersModel
= filtersModel
;
14 this.changesListModel
= changesListModel
;
15 this.savedQueriesModel
= savedQueriesModel
;
16 this.requestCounter
= {};
17 this.baseFilterState
= {};
18 this.uriProcessor
= null;
19 this.initializing
= false;
21 this.prevLoggedItems
= [];
25 OO
.initClass( mw
.rcfilters
.Controller
);
28 * Initialize the filter and parameter states
30 * @param {Array} filterStructure Filter definition and structure for the model
31 * @param {Object} [namespaceStructure] Namespace definition
32 * @param {Object} [tagList] Tag definition
34 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
35 var parsedSavedQueries
, limitDefault
,
40 $changesList
= $( '.mw-changeslist' ).first().contents();
43 if ( namespaceStructure
) {
45 $.each( namespaceStructure
, function ( namespaceID
, label
) {
46 // Build and clean up the individual namespace items definition
49 label
: label
|| mw
.msg( 'blanknamespace' ),
52 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
55 cssClass
: 'mw-changeslist-ns-' + namespaceID
60 title
: mw
.msg( 'namespaces' ),
63 // Group definition (single group)
64 name
: 'namespace', // parameter name is singular
65 type
: 'string_options',
66 title
: mw
.msg( 'namespaces' ),
67 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
76 title
: mw
.msg( 'rcfilters-view-tags' ),
79 // Group definition (single group)
80 name
: 'tagfilter', // Parameter name
81 type
: 'string_options',
82 title
: 'rcfilters-view-tags', // Message key
83 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
91 // Convert the default from the old preference
92 // since the limit preference actually affects more
93 // than just the RecentChanges page
94 limitDefault
= Number( mw
.user
.options
.get( 'rcfilters-rclimit', mw
.user
.options
.get( 'rclimit', '50' ) ) );
96 // Add parameter range operations
101 type
: 'single_option',
102 title
: '', // Because it's a hidden group, this title actually appears nowhere
104 allowArbitrary
: true,
105 validate
: $.isNumeric
,
106 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
107 'default': String( limitDefault
),
108 // Temporarily making this not sticky until we resolve the problem
109 // with the misleading preference. Note that if this is to be permanent
110 // we should remove all sticky behavior methods completely
113 filters
: [ 50, 100, 250, 500 ].map( function ( num
) {
114 return controller
._createFilterDataFromNumber( num
, num
);
119 type
: 'single_option',
120 title
: '', // Because it's a hidden group, this title actually appears nowhere
122 allowArbitrary
: true,
123 validate
: $.isNumeric
,
124 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
125 numToLabelFunc: function ( i
) {
126 return Number( i
) < 1 ?
127 ( Number( i
) * 24 ).toFixed( 2 ) :
130 'default': mw
.user
.options
.get( 'rcdays', '30' ),
131 // Temporarily making this not sticky while limit is not sticky, see above
134 // Hours (1, 2, 6, 12)
135 0.04166, 0.0833, 0.25, 0.5,
138 ].map( function ( num
) {
139 return controller
._createFilterDataFromNumber(
141 // Convert fractions of days to number of hours for the labels
142 num
< 1 ? Math
.round( num
* 24 ) : num
149 // Before we do anything, we need to see if we require additional items in the
150 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
151 // groups; if we ever expand it, this might need further generalization:
152 $.each( views
, function ( viewName
, viewData
) {
153 viewData
.groups
.forEach( function ( groupData
) {
154 var extraValues
= [];
155 if ( groupData
.allowArbitrary
) {
156 // If the value in the URI isn't in the group, add it
157 if ( uri
.query
[ groupData
.name
] !== undefined ) {
158 extraValues
.push( uri
.query
[ groupData
.name
] );
160 // If the default value isn't in the group, add it
161 if ( groupData
.default !== undefined ) {
162 extraValues
.push( String( groupData
.default ) );
164 controller
.addNumberValuesToGroup( groupData
, extraValues
);
169 // Initialize the model
170 this.filtersModel
.initializeFilters( filterStructure
, views
);
172 this._buildBaseFilterState();
174 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
179 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
181 parsedSavedQueries
= {};
184 // The queries are saved in a minimized state, so we need
185 // to send over the base state so the saved queries model
186 // can normalize them per each query item
187 this.savedQueriesModel
.initialize(
189 this._getBaseFilterState(),
190 // This is for backwards compatibility - delete all sticky filter states
191 Object
.keys( this.filtersModel
.getStickyFiltersState() )
194 // Check whether we need to load defaults.
195 // We do this by checking whether the current URI query
196 // contains any parameters recognized by the system.
197 // If it does, we load the given state.
198 // If it doesn't, we have no values at all, and we assume
199 // the user loads the base-page and we load defaults.
200 // Defaults should only be applied on load (if necessary)
202 this.initializing
= true;
204 this.savedQueriesModel
.getDefault() &&
205 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
207 // We have defaults from a saved query.
208 // We will load them straight-forward (as if
209 // they were clicked in the menu) so we trigger
210 // a full ajax request and change of URL
211 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
213 // There are either recognized parameters in the URL
214 // or there are none, but there is also no default
215 // saved query (so defaults are from the backend)
216 // We want to update the state but not fetch results
218 this.updateStateFromUrl( false );
220 // Update the changes list with the existing data
221 // so it gets processed
222 this.changesListModel
.update(
223 $changesList
.length
? $changesList
: 'NO_RESULTS',
224 $( 'fieldset.rcoptions' ).first(),
225 true // We're using existing DOM elements
229 this.initializing
= false;
230 this.switchView( 'default' );
232 this._scheduleLiveUpdate();
236 * Create filter data from a number, for the filters that are numerical value
238 * @param {Number} num Number
239 * @param {Number} numForDisplay Number for the label
240 * @return {Object} Filter data
242 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
245 label
: mw
.language
.convertNumber( numForDisplay
)
250 * Add an arbitrary values to groups that allow arbitrary values
252 * @param {Object} groupData Group data
253 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
255 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
256 var controller
= this;
258 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
260 // This is only true for single_option group
261 // We assume these are the only groups that will allow for
262 // arbitrary, since it doesn't make any sense for the other
264 arbitraryValues
.forEach( function ( val
) {
266 // If the group allows for arbitrary data
267 groupData
.allowArbitrary
&&
268 // and it is single_option (or string_options, but we
269 // don't have cases of those yet, nor do we plan to)
270 groupData
.type
=== 'single_option' &&
271 // and, if there is a validate method and it passes on
273 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
274 // but if that value isn't already in the definition
276 .map( function ( filterData
) {
277 return filterData
.name
;
279 .indexOf( val
) === -1
281 // Add the filter information
282 groupData
.filters
.push( controller
._createFilterDataFromNumber(
284 groupData
.numToLabelFunc
?
285 groupData
.numToLabelFunc( val
) :
289 // If there's a sort function set up, re-sort the values
290 if ( groupData
.sortFunc
) {
291 groupData
.filters
.sort( groupData
.sortFunc
);
298 * Switch the view of the filters model
300 * @param {string} view Requested view
302 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
303 this.filtersModel
.switchView( view
);
307 * Reset to default filters
309 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
310 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
312 this.updateChangesList();
316 * Empty all selected filters
318 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
319 var highlightedFilterNames
= this.filtersModel
320 .getHighlightedItems()
321 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
323 this.filtersModel
.emptyAllFilters();
324 this.filtersModel
.clearAllHighlightColors();
325 // Check all filter interactions
326 this.filtersModel
.reassessFilterInteractions();
328 this.updateChangesList();
330 if ( highlightedFilterNames
) {
331 this._trackHighlight( 'clearAll', highlightedFilterNames
);
336 * Update the selected state of a filter
338 * @param {string} filterName Filter name
339 * @param {boolean} [isSelected] Filter selected state
341 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
342 var filterItem
= this.filtersModel
.getItemByName( filterName
);
345 // If no filter was found, break
349 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
351 if ( filterItem
.isSelected() !== isSelected
) {
352 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
354 this.updateChangesList();
356 // Check filter interactions
357 this.filtersModel
.reassessFilterInteractions( filterItem
);
362 * Clear both highlight and selection of a filter
364 * @param {string} filterName Name of the filter item
366 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
367 var filterItem
= this.filtersModel
.getItemByName( filterName
),
368 isHighlighted
= filterItem
.isHighlighted();
370 if ( filterItem
.isSelected() || isHighlighted
) {
371 this.filtersModel
.clearHighlightColor( filterName
);
372 this.filtersModel
.toggleFilterSelected( filterName
, false );
373 this.updateChangesList();
374 this.filtersModel
.reassessFilterInteractions( filterItem
);
376 // Log filter grouping
377 this.trackFilterGroupings( 'removefilter' );
380 if ( isHighlighted
) {
381 this._trackHighlight( 'clear', filterName
);
386 * Toggle the highlight feature on and off
388 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
389 this.filtersModel
.toggleHighlight();
392 if ( this.filtersModel
.isHighlightEnabled() ) {
393 mw
.hook( 'RcFilters.highlight.enable' ).fire();
398 * Toggle the namespaces inverted feature on and off
400 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
401 this.filtersModel
.toggleInvertedNamespaces();
402 this.updateChangesList();
406 * Set the highlight color for a filter item
408 * @param {string} filterName Name of the filter item
409 * @param {string} color Selected color
411 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
412 this.filtersModel
.setHighlightColor( filterName
, color
);
414 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
418 * Clear highlight for a filter item
420 * @param {string} filterName Name of the filter item
422 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
423 this.filtersModel
.clearHighlightColor( filterName
);
425 this._trackHighlight( 'clear', filterName
);
429 * Enable or disable live updates.
430 * @param {boolean} enable True to enable, false to disable
432 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
433 this.changesListModel
.toggleLiveUpdate( enable
);
434 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
435 this.showNewChanges();
440 * Set a timeout for the next live update.
443 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
444 setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
448 * Perform a live update.
451 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
452 if ( !this._shouldCheckForNewChanges() ) {
453 // skip this turn and check back later
454 this._scheduleLiveUpdate();
458 this._checkForNewChanges()
459 .then( function ( data
) {
460 if ( !this._shouldCheckForNewChanges() ) {
461 // by the time the response is received,
462 // it may not be appropriate anymore
466 if ( data
.changes
!== 'NO_RESULTS' ) {
467 if ( this.changesListModel
.getLiveUpdate() ) {
468 return this.updateChangesList( false, null, true, false );
470 this.changesListModel
.setNewChangesExist( true );
474 .always( this._scheduleLiveUpdate
.bind( this ) );
478 * @return {boolean} It's appropriate to check for new changes now
481 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
482 var liveUpdateFeatureFlag
= mw
.config
.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
483 new mw
.Uri().query
.liveupdate
;
485 return !document
.hidden
&&
486 !this.changesListModel
.getNewChangesExist() &&
487 !this.updatingChangesList
&&
488 liveUpdateFeatureFlag
;
492 * Check if new changes, newer than those currently shown, are available
494 * @return {jQuery.Promise} Promise object that resolves after trying
495 * to fetch 1 change newer than the last known 'from' parameter value
499 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
500 return this._fetchChangesList(
504 from: this.changesListModel
.getNextFrom()
510 * Show the new changes
512 * @return {jQuery.Promise} Promise object that resolves after
513 * fetching and showing the new changes
515 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
516 return this.updateChangesList( false, null, true, true );
520 * Save the current model state as a saved query
522 * @param {string} [label] Label of the saved query
523 * @param {boolean} [setAsDefault=false] This query should be set as the default
525 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
527 highlightedItems
= {},
528 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
529 selectedState
= this.filtersModel
.getSelectedState();
531 // Prepare highlights
532 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
533 highlightedItems
[ item
.getName() ] = highlightEnabled
?
534 item
.getHighlightColor() : null;
536 // These are filter states; highlight is stored as boolean
537 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
539 // Delete all sticky filters
540 this._deleteStickyValuesFromFilterState( selectedState
);
543 queryID
= this.savedQueriesModel
.addNewQuery(
544 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
546 filters
: selectedState
,
547 highlights
: highlightedItems
,
548 invert
: this.filtersModel
.areNamespacesInverted()
552 if ( setAsDefault
) {
553 this.savedQueriesModel
.setDefault( queryID
);
557 this._saveSavedQueries();
561 * Remove a saved query
563 * @param {string} queryID Query id
565 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
566 this.savedQueriesModel
.removeQuery( queryID
);
568 this._saveSavedQueries();
572 * Rename a saved query
574 * @param {string} queryID Query id
575 * @param {string} newLabel New label for the query
577 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
578 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
581 queryItem
.updateLabel( newLabel
);
583 this._saveSavedQueries();
587 * Set a saved query as default
589 * @param {string} queryID Query Id. If null is given, default
592 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
593 this.savedQueriesModel
.setDefault( queryID
);
594 this._saveSavedQueries();
600 * @param {string} queryID Query id
602 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
603 var data
, highlights
,
604 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
607 data
= queryItem
.getData();
608 highlights
= data
.highlights
;
610 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
611 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
613 // Update model state from filters
614 this.filtersModel
.toggleFiltersSelected(
615 // Merge filters with sticky values
616 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
619 // Update namespace inverted property
620 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
622 // Update highlight state
623 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
624 this.filtersModel
.getItems().forEach( function ( filterItem
) {
625 var color
= highlights
[ filterItem
.getName() ];
627 filterItem
.setHighlightColor( color
);
629 filterItem
.clearHighlightColor();
633 // Check all filter interactions
634 this.filtersModel
.reassessFilterInteractions();
636 this.updateChangesList();
638 // Log filter grouping
639 this.trackFilterGroupings( 'savedfilters' );
644 * Check whether the current filter and highlight state exists
645 * in the saved queries model.
647 * @return {boolean} Query exists
649 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
650 var highlightedItems
= {},
651 selectedState
= this.filtersModel
.getSelectedState();
653 // Prepare highlights of the current query
654 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
655 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
657 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
659 // Remove sticky filters
660 this._deleteStickyValuesFromFilterState( selectedState
);
662 return this.savedQueriesModel
.findMatchingQuery(
664 filters
: selectedState
,
665 highlights
: highlightedItems
,
666 invert
: this.filtersModel
.areNamespacesInverted()
672 * Delete sticky filters from given object
674 * @param {Object} filterState Filter state
676 mw
.rcfilters
.Controller
.prototype._deleteStickyValuesFromFilterState = function ( filterState
) {
677 // Remove sticky filters
678 $.each( this.filtersModel
.getStickyFiltersState(), function ( filterName
) {
679 delete filterState
[ filterName
];
684 * Get an object representing the base state of parameters
687 * This is meant to make sure that the saved queries that are
688 * in memory are always the same structure as what we would get
689 * by calling the current model's "getSelectedState" and by checking
692 * In cases where a user saved a query when the system had a certain
693 * set of filters, and then a filter was added to the system, we want
694 * to make sure that the stored queries can still be comparable to
695 * the current state, which means that we need the base state for
698 * - Saved queries are stored in "minimal" view (only changed filters
699 * are stored); When we initialize the system, we merge each minimal
700 * query with the base state (using 'getNormalizedFilters') so all
701 * saved queries have the exact same structure as what we would get
702 * by checking the getSelectedState of the filter.
703 * - When we save the queries, we minimize the object to only represent
704 * whatever has actually changed, rather than store the entire
705 * object. To check what actually is different so we can store it,
706 * we need to obtain a base state to compare against, this is
707 * what #_getMinimalFilterList does
709 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
710 var defaultParams
= this.filtersModel
.getDefaultParams(),
711 highlightedItems
= {};
713 // Prepare highlights
714 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
715 highlightedItems
[ item
.getName() ] = null;
717 highlightedItems
.highlight
= false;
719 this.baseFilterState
= {
720 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
721 highlights
: highlightedItems
,
727 * Get an object representing the base filter state of both
728 * filters and highlights. The structure is similar to what we use
729 * to store each query in the saved queries object:
735 * filterName: (string|null)
739 * @return {Object} Object representing the base state of
740 * parameters and highlights
742 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
743 return this.baseFilterState
;
747 * Get an object that holds only the parameters and highlights that have
748 * values different than the base default value.
750 * This is the reverse of the normalization we do initially on loading and
751 * initializing the saved queries model.
753 * @param {Object} valuesObject Object representing the state of both
754 * filters and highlights in its normalized version, to be minimized.
755 * @return {Object} Minimal filters and highlights list
757 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
758 var result
= { filters
: {}, highlights
: {} },
759 baseState
= this._getBaseFilterState();
762 $.each( valuesObject
.filters
, function ( name
, value
) {
763 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
764 result
.filters
[ name
] = value
;
768 $.each( valuesObject
.highlights
, function ( name
, value
) {
769 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
770 result
.highlights
[ name
] = value
;
778 * Save the current state of the saved queries model with all
779 * query item representation in the user settings.
781 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
783 state
= this.savedQueriesModel
.getState(),
786 // Minimize before save
787 $.each( state
.queries
, function ( queryID
, info
) {
788 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
792 stringified
= JSON
.stringify( state
);
794 if ( stringified
.length
> 65535 ) {
795 // Sanity check, since the preference can only hold that.
799 // Save the preference
800 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
801 // Update the preference for this session
802 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
806 * Update sticky preferences with current model state
808 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
809 // Update default sticky values with selected, whether they came from
810 // the initial defaults or from the URL value that is being normalized
811 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
812 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
816 * Update the limit default value
818 * param {number} newValue New value
820 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
821 // HACK: Temporarily remove this from being sticky
825 if ( !$.isNumeric( newValue ) ) {
829 newValue = Number( newValue );
831 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
832 // Save the preference
833 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
834 // Update the preference for this session
835 mw.user.options.set( 'rcfilters-rclimit', newValue );
842 * Update the days default value
844 * param {number} newValue New value
846 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
847 // HACK: Temporarily remove this from being sticky
851 if ( !$.isNumeric( newValue ) ) {
855 newValue = Number( newValue );
857 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
858 // Save the preference
859 new mw.Api().saveOption( 'rcdays', newValue );
860 // Update the preference for this session
861 mw.user.options.set( 'rcdays', newValue );
868 * Synchronize the URL with the current state of the filters
869 * without adding an history entry.
871 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
872 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
876 * Update filter state (selection and highlighting) based
877 * on current URL values.
879 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
880 * list based on the updated model.
882 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
883 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
885 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
887 // Update the sticky preferences, in case we received a value
889 this.updateStickyPreferences();
891 // Only update and fetch new results if it is requested
892 if ( fetchChangesList
) {
893 this.updateChangesList();
898 * Update the list of changes and notify the model
900 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
901 * @param {Object} [params] Extra parameters to add to the API call
902 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
903 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
904 * @return {jQuery.Promise} Promise that is resolved when the update is complete
906 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( updateUrl
, params
, isLiveUpdate
, invalidateCurrentChanges
) {
907 updateUrl
= updateUrl
=== undefined ? true : updateUrl
;
908 invalidateCurrentChanges
= invalidateCurrentChanges
=== undefined ? true : invalidateCurrentChanges
;
910 this._updateURL( params
);
912 if ( invalidateCurrentChanges
) {
913 this.changesListModel
.invalidate();
915 this.changesListModel
.setNewChangesExist( false );
916 this.updatingChangesList
= true;
917 return this._fetchChangesList()
920 function ( pieces
) {
921 var $changesListContent
= pieces
.changes
,
922 $fieldset
= pieces
.fieldset
;
923 this.changesListModel
.update( $changesListContent
, $fieldset
, false, isLiveUpdate
);
925 // Do nothing for failure
927 .always( function () {
928 this.updatingChangesList
= false;
933 * Get an object representing the default parameter state, whether
934 * it is from the model defaults or from the saved queries.
936 * @return {Object} Default parameters
938 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
939 var data
, queryHighlights
,
941 savedHighlights
= {},
942 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
944 if ( defaultSavedQueryItem
) {
945 data
= defaultSavedQueryItem
.getData();
947 queryHighlights
= data
.highlights
|| {};
948 savedParams
= this.filtersModel
.getParametersFromFilters(
949 // Merge filters with sticky values
950 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
953 // Translate highlights to parameters
954 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
955 $.each( queryHighlights
, function ( filterName
, color
) {
956 if ( filterName
!== 'highlights' ) {
957 savedHighlights
[ filterName
+ '_color' ] = color
;
961 return $.extend( true, {}, savedParams
, savedHighlights
);
964 return this.filtersModel
.getDefaultParams();
968 * Update the URL of the page to reflect current filters
970 * This should not be called directly from outside the controller.
971 * If an action requires changing the URL, it should either use the
972 * highlighting actions below, or call #updateChangesList which does
973 * the uri corrections already.
975 * @param {Object} [params] Extra parameters to add to the API call
977 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
978 var currentUri
= new mw
.Uri(),
979 updatedUri
= this._getUpdatedUri();
981 updatedUri
.extend( params
|| {} );
984 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
985 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
987 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
992 * Get an updated mw.Uri object based on the model state
994 * @return {mw.Uri} Updated Uri
996 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
997 var uri
= new mw
.Uri();
1000 uri
.query
= this.uriProcessor
.minimizeQuery(
1004 // We want to retain unrecognized params
1005 // The uri params from model will override
1006 // any recognized value in the current uri
1007 // query, retain unrecognized params, and
1008 // the result will then be minimized
1010 this.uriProcessor
.getUriParametersFromModel(),
1019 * Fetch the list of changes from the server for the current filters
1021 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1022 * not to invalidate each other.
1023 * @param {Object} [params={}] Parameters to add to the query
1025 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1026 * or with a string denoting no results.
1028 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function ( counterId
, params
) {
1029 var uri
= this._getUpdatedUri(),
1030 stickyParams
= this.filtersModel
.getStickyParams(),
1034 counterId
= counterId
|| 'updateChangesList';
1035 params
= params
|| {};
1037 uri
.extend( params
);
1039 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1040 requestId
= ++this.requestCounter
[ counterId
];
1041 latestRequest = function () {
1042 return requestId
=== this.requestCounter
[ counterId
];
1045 // Sticky parameters override the URL params
1046 // this is to make sure that whether we represent
1047 // the sticky params in the URL or not (they may
1048 // be normalized out) the sticky parameters are
1049 // always being sent to the server with their
1050 // current/default values
1051 uri
.extend( stickyParams
);
1053 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1058 if ( !latestRequest() ) {
1059 return $.Deferred().reject();
1062 $parsed
= $( $.parseHTML( html
) );
1066 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1068 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1072 function ( responseObj
) {
1075 if ( !latestRequest() ) {
1076 return $.Deferred().reject();
1079 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
1081 // Force a resolve state to this promise
1082 return $.Deferred().resolve( {
1083 changes
: 'NO_RESULTS',
1084 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1091 * Track usage of highlight feature
1093 * @param {string} action
1094 * @param {Array|Object|string} filters
1096 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1097 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1098 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1100 'event.ChangesListHighlights',
1104 userId
: mw
.user
.getId()
1110 * Track filter grouping usage
1112 * @param {string} action Action taken
1114 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1115 var controller
= this,
1116 rightNow
= new Date().getTime(),
1117 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1118 // Get all current filters
1119 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1120 return item
.getName();
1123 action
= action
|| 'filtermenu';
1125 // Check if these filters were the ones we just logged previously
1126 // (Don't log the same grouping twice, in case the user opens/closes)
1127 // the menu without action, or with the same result
1129 // Only log if the two arrays are different in size
1130 filters
.length
!== this.prevLoggedItems
.length
||
1131 // Or if any filters are not the same as the cached filters
1132 filters
.some( function ( filterName
) {
1133 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1135 // Or if any cached filters are not the same as given filters
1136 this.prevLoggedItems
.some( function ( filterName
) {
1137 return filters
.indexOf( filterName
) === -1;
1140 filters
.forEach( function ( filterName
) {
1142 'event.ChangesListFilterGrouping',
1145 groupIdentifier
: randomIdentifier
,
1147 userId
: mw
.user
.getId()
1152 // Cache the filter names
1153 this.prevLoggedItems
= filters
;
1156 }( mediaWiki
, jQuery
) );