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
),
109 filters
: [ 50, 100, 250, 500 ].map( function ( num
) {
110 return controller
._createFilterDataFromNumber( num
, num
);
115 type
: 'single_option',
116 title
: '', // Because it's a hidden group, this title actually appears nowhere
118 allowArbitrary
: true,
119 validate
: $.isNumeric
,
120 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
121 numToLabelFunc: function ( i
) {
122 return Number( i
) < 1 ?
123 ( Number( i
) * 24 ).toFixed( 2 ) :
126 'default': mw
.user
.options
.get( 'rcdays', '30' ),
129 // Hours (1, 2, 6, 12)
130 0.04166, 0.0833, 0.25, 0.5,
133 ].map( function ( num
) {
134 return controller
._createFilterDataFromNumber(
136 // Convert fractions of days to number of hours for the labels
137 num
< 1 ? Math
.round( num
* 24 ) : num
149 title
: '', // Because it's a hidden group, this title actually appears nowhere
155 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
162 // Before we do anything, we need to see if we require additional items in the
163 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
164 // groups; if we ever expand it, this might need further generalization:
165 $.each( views
, function ( viewName
, viewData
) {
166 viewData
.groups
.forEach( function ( groupData
) {
167 var extraValues
= [];
168 if ( groupData
.allowArbitrary
) {
169 // If the value in the URI isn't in the group, add it
170 if ( uri
.query
[ groupData
.name
] !== undefined ) {
171 extraValues
.push( uri
.query
[ groupData
.name
] );
173 // If the default value isn't in the group, add it
174 if ( groupData
.default !== undefined ) {
175 extraValues
.push( String( groupData
.default ) );
177 controller
.addNumberValuesToGroup( groupData
, extraValues
);
182 // Initialize the model
183 this.filtersModel
.initializeFilters( filterStructure
, views
);
185 this._buildBaseFilterState();
187 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
192 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
194 parsedSavedQueries
= {};
197 // The queries are saved in a minimized state, so we need
198 // to send over the base state so the saved queries model
199 // can normalize them per each query item
200 this.savedQueriesModel
.initialize(
202 this._getBaseFilterState(),
203 // This is for backwards compatibility - delete all sticky filter states
204 Object
.keys( this.filtersModel
.getStickyFiltersState() )
207 // Check whether we need to load defaults.
208 // We do this by checking whether the current URI query
209 // contains any parameters recognized by the system.
210 // If it does, we load the given state.
211 // If it doesn't, we have no values at all, and we assume
212 // the user loads the base-page and we load defaults.
213 // Defaults should only be applied on load (if necessary)
215 this.initializing
= true;
217 this.savedQueriesModel
.getDefault() &&
218 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
220 // We have defaults from a saved query.
221 // We will load them straight-forward (as if
222 // they were clicked in the menu) so we trigger
223 // a full ajax request and change of URL
224 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
226 // There are either recognized parameters in the URL
227 // or there are none, but there is also no default
228 // saved query (so defaults are from the backend)
229 // We want to update the state but not fetch results
231 this.updateStateFromUrl( false );
233 // Update the changes list with the existing data
234 // so it gets processed
235 this.changesListModel
.update(
236 $changesList
.length
? $changesList
: 'NO_RESULTS',
237 $( 'fieldset.rcoptions' ).first(),
238 true // We're using existing DOM elements
242 this.initializing
= false;
243 this.switchView( 'default' );
245 this._scheduleLiveUpdate();
249 * Create filter data from a number, for the filters that are numerical value
251 * @param {Number} num Number
252 * @param {Number} numForDisplay Number for the label
253 * @return {Object} Filter data
255 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
258 label
: mw
.language
.convertNumber( numForDisplay
)
263 * Add an arbitrary values to groups that allow arbitrary values
265 * @param {Object} groupData Group data
266 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
268 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
269 var controller
= this;
271 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
273 // This is only true for single_option group
274 // We assume these are the only groups that will allow for
275 // arbitrary, since it doesn't make any sense for the other
277 arbitraryValues
.forEach( function ( val
) {
279 // If the group allows for arbitrary data
280 groupData
.allowArbitrary
&&
281 // and it is single_option (or string_options, but we
282 // don't have cases of those yet, nor do we plan to)
283 groupData
.type
=== 'single_option' &&
284 // and, if there is a validate method and it passes on
286 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
287 // but if that value isn't already in the definition
289 .map( function ( filterData
) {
290 return filterData
.name
;
292 .indexOf( val
) === -1
294 // Add the filter information
295 groupData
.filters
.push( controller
._createFilterDataFromNumber(
297 groupData
.numToLabelFunc
?
298 groupData
.numToLabelFunc( val
) :
302 // If there's a sort function set up, re-sort the values
303 if ( groupData
.sortFunc
) {
304 groupData
.filters
.sort( groupData
.sortFunc
);
311 * Switch the view of the filters model
313 * @param {string} view Requested view
315 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
316 this.filtersModel
.switchView( view
);
320 * Reset to default filters
322 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
323 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
325 this.updateChangesList();
329 * Empty all selected filters
331 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
332 var highlightedFilterNames
= this.filtersModel
333 .getHighlightedItems()
334 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
336 this.filtersModel
.emptyAllFilters();
337 this.filtersModel
.clearAllHighlightColors();
338 // Check all filter interactions
339 this.filtersModel
.reassessFilterInteractions();
341 this.updateChangesList();
343 if ( highlightedFilterNames
) {
344 this._trackHighlight( 'clearAll', highlightedFilterNames
);
349 * Update the selected state of a filter
351 * @param {string} filterName Filter name
352 * @param {boolean} [isSelected] Filter selected state
354 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
355 var filterItem
= this.filtersModel
.getItemByName( filterName
);
358 // If no filter was found, break
362 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
364 if ( filterItem
.isSelected() !== isSelected
) {
365 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
367 this.updateChangesList();
369 // Check filter interactions
370 this.filtersModel
.reassessFilterInteractions( filterItem
);
375 * Clear both highlight and selection of a filter
377 * @param {string} filterName Name of the filter item
379 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
380 var filterItem
= this.filtersModel
.getItemByName( filterName
),
381 isHighlighted
= filterItem
.isHighlighted();
383 if ( filterItem
.isSelected() || isHighlighted
) {
384 this.filtersModel
.clearHighlightColor( filterName
);
385 this.filtersModel
.toggleFilterSelected( filterName
, false );
386 this.updateChangesList();
387 this.filtersModel
.reassessFilterInteractions( filterItem
);
389 // Log filter grouping
390 this.trackFilterGroupings( 'removefilter' );
393 if ( isHighlighted
) {
394 this._trackHighlight( 'clear', filterName
);
399 * Toggle the highlight feature on and off
401 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
402 this.filtersModel
.toggleHighlight();
405 if ( this.filtersModel
.isHighlightEnabled() ) {
406 mw
.hook( 'RcFilters.highlight.enable' ).fire();
411 * Toggle the namespaces inverted feature on and off
413 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
414 this.filtersModel
.toggleInvertedNamespaces();
415 this.updateChangesList();
419 * Set the highlight color for a filter item
421 * @param {string} filterName Name of the filter item
422 * @param {string} color Selected color
424 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
425 this.filtersModel
.setHighlightColor( filterName
, color
);
427 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
431 * Clear highlight for a filter item
433 * @param {string} filterName Name of the filter item
435 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
436 this.filtersModel
.clearHighlightColor( filterName
);
438 this._trackHighlight( 'clear', filterName
);
442 * Enable or disable live updates.
443 * @param {boolean} enable True to enable, false to disable
445 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
446 this.changesListModel
.toggleLiveUpdate( enable
);
447 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
448 this.showNewChanges();
453 * Set a timeout for the next live update.
456 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
457 setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
461 * Perform a live update.
464 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
465 if ( !this._shouldCheckForNewChanges() ) {
466 // skip this turn and check back later
467 this._scheduleLiveUpdate();
471 this._checkForNewChanges()
472 .then( function ( data
) {
473 if ( !this._shouldCheckForNewChanges() ) {
474 // by the time the response is received,
475 // it may not be appropriate anymore
479 if ( data
.changes
!== 'NO_RESULTS' ) {
480 if ( this.changesListModel
.getLiveUpdate() ) {
481 return this.updateChangesList( false, null, true, false );
483 this.changesListModel
.setNewChangesExist( true );
487 .always( this._scheduleLiveUpdate
.bind( this ) );
491 * @return {boolean} It's appropriate to check for new changes now
494 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
495 var liveUpdateFeatureFlag
= mw
.config
.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
496 new mw
.Uri().query
.liveupdate
;
498 return !document
.hidden
&&
499 !this.changesListModel
.getNewChangesExist() &&
500 !this.updatingChangesList
&&
501 liveUpdateFeatureFlag
;
505 * Check if new changes, newer than those currently shown, are available
507 * @return {jQuery.Promise} Promise object that resolves after trying
508 * to fetch 1 change newer than the last known 'from' parameter value
512 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
513 return this._fetchChangesList(
517 from: this.changesListModel
.getNextFrom()
523 * Show the new changes
525 * @return {jQuery.Promise} Promise object that resolves after
526 * fetching and showing the new changes
528 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
529 return this.updateChangesList( false, null, true, true );
533 * Save the current model state as a saved query
535 * @param {string} [label] Label of the saved query
536 * @param {boolean} [setAsDefault=false] This query should be set as the default
538 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
540 highlightedItems
= {},
541 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
542 selectedState
= this.filtersModel
.getSelectedState();
544 // Prepare highlights
545 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
546 highlightedItems
[ item
.getName() ] = highlightEnabled
?
547 item
.getHighlightColor() : null;
549 // These are filter states; highlight is stored as boolean
550 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
552 // Delete all sticky filters
553 this._deleteStickyValuesFromFilterState( selectedState
);
556 queryID
= this.savedQueriesModel
.addNewQuery(
557 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
559 filters
: selectedState
,
560 highlights
: highlightedItems
,
561 invert
: this.filtersModel
.areNamespacesInverted()
565 if ( setAsDefault
) {
566 this.savedQueriesModel
.setDefault( queryID
);
570 this._saveSavedQueries();
574 * Remove a saved query
576 * @param {string} queryID Query id
578 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
579 this.savedQueriesModel
.removeQuery( queryID
);
581 this._saveSavedQueries();
585 * Rename a saved query
587 * @param {string} queryID Query id
588 * @param {string} newLabel New label for the query
590 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
591 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
594 queryItem
.updateLabel( newLabel
);
596 this._saveSavedQueries();
600 * Set a saved query as default
602 * @param {string} queryID Query Id. If null is given, default
605 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
606 this.savedQueriesModel
.setDefault( queryID
);
607 this._saveSavedQueries();
613 * @param {string} queryID Query id
615 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
616 var data
, highlights
,
617 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
620 data
= queryItem
.getData();
621 highlights
= data
.highlights
;
623 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
624 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
626 // Update model state from filters
627 this.filtersModel
.toggleFiltersSelected(
628 // Merge filters with sticky values
629 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
632 // Update namespace inverted property
633 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
635 // Update highlight state
636 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
637 this.filtersModel
.getItems().forEach( function ( filterItem
) {
638 var color
= highlights
[ filterItem
.getName() ];
640 filterItem
.setHighlightColor( color
);
642 filterItem
.clearHighlightColor();
646 // Check all filter interactions
647 this.filtersModel
.reassessFilterInteractions();
649 this.updateChangesList();
651 // Log filter grouping
652 this.trackFilterGroupings( 'savedfilters' );
657 * Check whether the current filter and highlight state exists
658 * in the saved queries model.
660 * @return {boolean} Query exists
662 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
663 var highlightedItems
= {},
664 selectedState
= this.filtersModel
.getSelectedState();
666 // Prepare highlights of the current query
667 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
668 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
670 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
672 // Remove sticky filters
673 this._deleteStickyValuesFromFilterState( selectedState
);
675 return this.savedQueriesModel
.findMatchingQuery(
677 filters
: selectedState
,
678 highlights
: highlightedItems
,
679 invert
: this.filtersModel
.areNamespacesInverted()
685 * Delete sticky filters from given object
687 * @param {Object} filterState Filter state
689 mw
.rcfilters
.Controller
.prototype._deleteStickyValuesFromFilterState = function ( filterState
) {
690 // Remove sticky filters
691 $.each( this.filtersModel
.getStickyFiltersState(), function ( filterName
) {
692 delete filterState
[ filterName
];
697 * Get an object representing the base state of parameters
700 * This is meant to make sure that the saved queries that are
701 * in memory are always the same structure as what we would get
702 * by calling the current model's "getSelectedState" and by checking
705 * In cases where a user saved a query when the system had a certain
706 * set of filters, and then a filter was added to the system, we want
707 * to make sure that the stored queries can still be comparable to
708 * the current state, which means that we need the base state for
711 * - Saved queries are stored in "minimal" view (only changed filters
712 * are stored); When we initialize the system, we merge each minimal
713 * query with the base state (using 'getNormalizedFilters') so all
714 * saved queries have the exact same structure as what we would get
715 * by checking the getSelectedState of the filter.
716 * - When we save the queries, we minimize the object to only represent
717 * whatever has actually changed, rather than store the entire
718 * object. To check what actually is different so we can store it,
719 * we need to obtain a base state to compare against, this is
720 * what #_getMinimalFilterList does
722 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
723 var defaultParams
= this.filtersModel
.getDefaultParams(),
724 highlightedItems
= {};
726 // Prepare highlights
727 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
728 highlightedItems
[ item
.getName() ] = null;
730 highlightedItems
.highlight
= false;
732 this.baseFilterState
= {
733 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
734 highlights
: highlightedItems
,
740 * Get an object representing the base filter state of both
741 * filters and highlights. The structure is similar to what we use
742 * to store each query in the saved queries object:
748 * filterName: (string|null)
752 * @return {Object} Object representing the base state of
753 * parameters and highlights
755 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
756 return this.baseFilterState
;
760 * Get an object that holds only the parameters and highlights that have
761 * values different than the base default value.
763 * This is the reverse of the normalization we do initially on loading and
764 * initializing the saved queries model.
766 * @param {Object} valuesObject Object representing the state of both
767 * filters and highlights in its normalized version, to be minimized.
768 * @return {Object} Minimal filters and highlights list
770 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
771 var result
= { filters
: {}, highlights
: {} },
772 baseState
= this._getBaseFilterState();
775 $.each( valuesObject
.filters
, function ( name
, value
) {
776 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
777 result
.filters
[ name
] = value
;
781 $.each( valuesObject
.highlights
, function ( name
, value
) {
782 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
783 result
.highlights
[ name
] = value
;
791 * Save the current state of the saved queries model with all
792 * query item representation in the user settings.
794 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
796 state
= this.savedQueriesModel
.getState(),
799 // Minimize before save
800 $.each( state
.queries
, function ( queryID
, info
) {
801 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
805 stringified
= JSON
.stringify( state
);
807 if ( stringified
.length
> 65535 ) {
808 // Sanity check, since the preference can only hold that.
812 // Save the preference
813 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
814 // Update the preference for this session
815 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
819 * Update sticky preferences with current model state
821 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
822 // Update default sticky values with selected, whether they came from
823 // the initial defaults or from the URL value that is being normalized
824 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
825 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
827 // TODO: Make these automatic by having the model go over sticky
828 // items and update their default values automatically
832 * Update the limit default value
834 * @param {number} newValue New value
836 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
837 if ( !$.isNumeric( newValue
) ) {
841 newValue
= Number( newValue
);
843 if ( mw
.user
.options
.get( 'rcfilters-rclimit' ) !== newValue
) {
844 // Save the preference
845 new mw
.Api().saveOption( 'rcfilters-rclimit', newValue
);
846 // Update the preference for this session
847 mw
.user
.options
.set( 'rcfilters-rclimit', newValue
);
852 * Update the days default value
854 * @param {number} newValue New value
856 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
857 if ( !$.isNumeric( newValue
) ) {
861 newValue
= Number( newValue
);
863 if ( mw
.user
.options
.get( 'rcdays' ) !== newValue
) {
864 // Save the preference
865 new mw
.Api().saveOption( 'rcdays', newValue
);
866 // Update the preference for this session
867 mw
.user
.options
.set( 'rcdays', newValue
);
872 * Update the group by page default value
874 * @param {number} newValue New value
876 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
877 if ( !$.isNumeric( newValue
) ) {
881 newValue
= Number( newValue
);
883 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
884 // Save the preference
885 new mw
.Api().saveOption( 'usenewrc', newValue
);
886 // Update the preference for this session
887 mw
.user
.options
.set( 'usenewrc', newValue
);
892 * Synchronize the URL with the current state of the filters
893 * without adding an history entry.
895 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
896 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
900 * Update filter state (selection and highlighting) based
901 * on current URL values.
903 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
904 * list based on the updated model.
906 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
907 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
909 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
911 // Update the sticky preferences, in case we received a value
913 this.updateStickyPreferences();
915 // Only update and fetch new results if it is requested
916 if ( fetchChangesList
) {
917 this.updateChangesList();
922 * Update the list of changes and notify the model
924 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
925 * @param {Object} [params] Extra parameters to add to the API call
926 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
927 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
928 * @return {jQuery.Promise} Promise that is resolved when the update is complete
930 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( updateUrl
, params
, isLiveUpdate
, invalidateCurrentChanges
) {
931 updateUrl
= updateUrl
=== undefined ? true : updateUrl
;
932 invalidateCurrentChanges
= invalidateCurrentChanges
=== undefined ? true : invalidateCurrentChanges
;
934 this._updateURL( params
);
936 if ( invalidateCurrentChanges
) {
937 this.changesListModel
.invalidate();
939 this.changesListModel
.setNewChangesExist( false );
940 this.updatingChangesList
= true;
941 return this._fetchChangesList()
944 function ( pieces
) {
945 var $changesListContent
= pieces
.changes
,
946 $fieldset
= pieces
.fieldset
;
947 this.changesListModel
.update( $changesListContent
, $fieldset
, false, isLiveUpdate
);
949 // Do nothing for failure
951 .always( function () {
952 this.updatingChangesList
= false;
957 * Get an object representing the default parameter state, whether
958 * it is from the model defaults or from the saved queries.
960 * @return {Object} Default parameters
962 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
963 var data
, queryHighlights
,
965 savedHighlights
= {},
966 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
968 if ( defaultSavedQueryItem
) {
969 data
= defaultSavedQueryItem
.getData();
971 queryHighlights
= data
.highlights
|| {};
972 savedParams
= this.filtersModel
.getParametersFromFilters(
973 // Merge filters with sticky values
974 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
977 // Translate highlights to parameters
978 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
979 $.each( queryHighlights
, function ( filterName
, color
) {
980 if ( filterName
!== 'highlights' ) {
981 savedHighlights
[ filterName
+ '_color' ] = color
;
985 return $.extend( true, {}, savedParams
, savedHighlights
);
988 return this.filtersModel
.getDefaultParams();
992 * Update the URL of the page to reflect current filters
994 * This should not be called directly from outside the controller.
995 * If an action requires changing the URL, it should either use the
996 * highlighting actions below, or call #updateChangesList which does
997 * the uri corrections already.
999 * @param {Object} [params] Extra parameters to add to the API call
1001 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1002 var currentUri
= new mw
.Uri(),
1003 updatedUri
= this._getUpdatedUri();
1005 updatedUri
.extend( params
|| {} );
1008 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1009 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1011 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1016 * Get an updated mw.Uri object based on the model state
1018 * @return {mw.Uri} Updated Uri
1020 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1021 var uri
= new mw
.Uri();
1024 uri
.query
= this.uriProcessor
.minimizeQuery(
1028 // We want to retain unrecognized params
1029 // The uri params from model will override
1030 // any recognized value in the current uri
1031 // query, retain unrecognized params, and
1032 // the result will then be minimized
1034 this.uriProcessor
.getUriParametersFromModel(),
1043 * Fetch the list of changes from the server for the current filters
1045 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1046 * not to invalidate each other.
1047 * @param {Object} [params={}] Parameters to add to the query
1049 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1050 * or with a string denoting no results.
1052 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function ( counterId
, params
) {
1053 var uri
= this._getUpdatedUri(),
1054 stickyParams
= this.filtersModel
.getStickyParams(),
1058 counterId
= counterId
|| 'updateChangesList';
1059 params
= params
|| {};
1061 uri
.extend( params
);
1063 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1064 requestId
= ++this.requestCounter
[ counterId
];
1065 latestRequest = function () {
1066 return requestId
=== this.requestCounter
[ counterId
];
1069 // Sticky parameters override the URL params
1070 // this is to make sure that whether we represent
1071 // the sticky params in the URL or not (they may
1072 // be normalized out) the sticky parameters are
1073 // always being sent to the server with their
1074 // current/default values
1075 uri
.extend( stickyParams
);
1077 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1082 if ( !latestRequest() ) {
1083 return $.Deferred().reject();
1086 $parsed
= $( $.parseHTML( html
) );
1090 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1092 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1096 function ( responseObj
) {
1099 if ( !latestRequest() ) {
1100 return $.Deferred().reject();
1103 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
1105 // Force a resolve state to this promise
1106 return $.Deferred().resolve( {
1107 changes
: 'NO_RESULTS',
1108 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1115 * Track usage of highlight feature
1117 * @param {string} action
1118 * @param {Array|Object|string} filters
1120 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1121 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1122 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1124 'event.ChangesListHighlights',
1128 userId
: mw
.user
.getId()
1134 * Track filter grouping usage
1136 * @param {string} action Action taken
1138 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1139 var controller
= this,
1140 rightNow
= new Date().getTime(),
1141 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1142 // Get all current filters
1143 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1144 return item
.getName();
1147 action
= action
|| 'filtermenu';
1149 // Check if these filters were the ones we just logged previously
1150 // (Don't log the same grouping twice, in case the user opens/closes)
1151 // the menu without action, or with the same result
1153 // Only log if the two arrays are different in size
1154 filters
.length
!== this.prevLoggedItems
.length
||
1155 // Or if any filters are not the same as the cached filters
1156 filters
.some( function ( filterName
) {
1157 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1159 // Or if any cached filters are not the same as given filters
1160 this.prevLoggedItems
.some( function ( filterName
) {
1161 return filters
.indexOf( filterName
) === -1;
1164 filters
.forEach( function ( filterName
) {
1166 'event.ChangesListFilterGrouping',
1169 groupIdentifier
: randomIdentifier
,
1171 userId
: mw
.user
.getId()
1176 // Cache the filter names
1177 this.prevLoggedItems
= filters
;
1180 }( mediaWiki
, jQuery
) );