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;
25 this.prevLoggedItems
= [];
27 this.FILTER_CHANGE
= 'filterChange';
28 this.SHOW_NEW_CHANGES
= 'showNewChanges';
29 this.LIVE_UPDATE
= 'liveUpdate';
33 OO
.initClass( mw
.rcfilters
.Controller
);
36 * Initialize the filter and parameter states
38 * @param {Array} filterStructure Filter definition and structure for the model
39 * @param {Object} [namespaceStructure] Namespace definition
40 * @param {Object} [tagList] Tag definition
42 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
43 var parsedSavedQueries
,
44 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
49 $changesList
= $( '.mw-changeslist' ).first().contents();
52 if ( namespaceStructure
) {
54 $.each( namespaceStructure
, function ( namespaceID
, label
) {
55 // Build and clean up the individual namespace items definition
58 label
: label
|| mw
.msg( 'blanknamespace' ),
61 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
64 cssClass
: 'mw-changeslist-ns-' + namespaceID
69 title
: mw
.msg( 'namespaces' ),
72 // Group definition (single group)
73 name
: 'namespace', // parameter name is singular
74 type
: 'string_options',
75 title
: mw
.msg( 'namespaces' ),
76 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
85 title
: mw
.msg( 'rcfilters-view-tags' ),
88 // Group definition (single group)
89 name
: 'tagfilter', // Parameter name
90 type
: 'string_options',
91 title
: 'rcfilters-view-tags', // Message key
92 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
100 // Add parameter range operations
105 type
: 'single_option',
106 title
: '', // Because it's a hidden group, this title actually appears nowhere
108 allowArbitrary
: true,
109 validate
: $.isNumeric
,
111 min
: 0, // The server normalizes negative numbers to 0 results
114 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
115 'default': displayConfig
.limitDefault
,
116 // Temporarily making this not sticky until we resolve the problem
117 // with the misleading preference. Note that if this is to be permanent
118 // we should remove all sticky behavior methods completely
121 excludedFromSavedQueries
: true,
122 filters
: displayConfig
.limitArray
.map( function ( num
) {
123 return controller
._createFilterDataFromNumber( num
, num
);
128 type
: 'single_option',
129 title
: '', // Because it's a hidden group, this title actually appears nowhere
131 allowArbitrary
: true,
132 validate
: $.isNumeric
,
135 max
: displayConfig
.maxDays
137 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
138 numToLabelFunc: function ( i
) {
139 return Number( i
) < 1 ?
140 ( Number( i
) * 24 ).toFixed( 2 ) :
143 'default': displayConfig
.daysDefault
,
144 // Temporarily making this not sticky while limit is not sticky, see above
146 excludedFromSavedQueries
: true,
148 // Hours (1, 2, 6, 12)
149 0.04166, 0.0833, 0.25, 0.5
151 ].concat( displayConfig
.daysArray
)
152 .map( function ( num
) {
153 return controller
._createFilterDataFromNumber(
155 // Convert fractions of days to number of hours for the labels
156 num
< 1 ? Math
.round( num
* 24 ) : num
168 title
: '', // Because it's a hidden group, this title actually appears nowhere
174 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
181 // Before we do anything, we need to see if we require additional items in the
182 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
183 // groups; if we ever expand it, this might need further generalization:
184 $.each( views
, function ( viewName
, viewData
) {
185 viewData
.groups
.forEach( function ( groupData
) {
186 var extraValues
= [];
187 if ( groupData
.allowArbitrary
) {
188 // If the value in the URI isn't in the group, add it
189 if ( uri
.query
[ groupData
.name
] !== undefined ) {
190 extraValues
.push( uri
.query
[ groupData
.name
] );
192 // If the default value isn't in the group, add it
193 if ( groupData
.default !== undefined ) {
194 extraValues
.push( String( groupData
.default ) );
196 controller
.addNumberValuesToGroup( groupData
, extraValues
);
201 // Initialize the model
202 this.filtersModel
.initializeFilters( filterStructure
, views
);
204 this._buildBaseFilterState();
206 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
210 if ( !mw
.user
.isAnon() ) {
212 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
214 parsedSavedQueries
= {};
217 // The queries are saved in a minimized state, so we need
218 // to send over the base state so the saved queries model
219 // can normalize them per each query item
220 this.savedQueriesModel
.initialize(
222 this._getBaseFilterState(),
223 // This is for backwards compatibility - delete all excluded filter states
224 Object
.keys( this.filtersModel
.getExcludedFiltersState() )
228 // Check whether we need to load defaults.
229 // We do this by checking whether the current URI query
230 // contains any parameters recognized by the system.
231 // If it does, we load the given state.
232 // If it doesn't, we have no values at all, and we assume
233 // the user loads the base-page and we load defaults.
234 // Defaults should only be applied on load (if necessary)
236 this.initializing
= true;
238 !mw
.user
.isAnon() && this.savedQueriesModel
.getDefault() &&
239 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
241 // We have defaults from a saved query.
242 // We will load them straight-forward (as if
243 // they were clicked in the menu) so we trigger
244 // a full ajax request and change of URL
245 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
247 // There are either recognized parameters in the URL
248 // or there are none, but there is also no default
249 // saved query (so defaults are from the backend)
250 // We want to update the state but not fetch results
252 this.updateStateFromUrl( false );
254 // Update the changes list with the existing data
255 // so it gets processed
256 this.changesListModel
.update(
257 $changesList
.length
? $changesList
: 'NO_RESULTS',
258 $( 'fieldset.cloptions' ).first(),
259 true // We're using existing DOM elements
263 this.initializing
= false;
264 this.switchView( 'default' );
266 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
267 if ( this.pollingRate
) {
268 this._scheduleLiveUpdate();
273 * Create filter data from a number, for the filters that are numerical value
275 * @param {Number} num Number
276 * @param {Number} numForDisplay Number for the label
277 * @return {Object} Filter data
279 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
282 label
: mw
.language
.convertNumber( numForDisplay
)
287 * Add an arbitrary values to groups that allow arbitrary values
289 * @param {Object} groupData Group data
290 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
292 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
293 var controller
= this,
294 normalizeWithinRange = function ( range
, val
) {
295 if ( val
< range
.min
) {
296 return range
.min
; // Min
297 } else if ( val
>= range
.max
) {
298 return range
.max
; // Max
303 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
305 // Normalize the arbitrary values and the default value for a range
306 if ( groupData
.range
) {
307 arbitraryValues
= arbitraryValues
.map( function ( val
) {
308 return normalizeWithinRange( groupData
.range
, val
);
311 // Normalize the default, since that's user defined
312 if ( groupData
.default !== undefined ) {
313 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
317 // This is only true for single_option group
318 // We assume these are the only groups that will allow for
319 // arbitrary, since it doesn't make any sense for the other
321 arbitraryValues
.forEach( function ( val
) {
323 // If the group allows for arbitrary data
324 groupData
.allowArbitrary
&&
325 // and it is single_option (or string_options, but we
326 // don't have cases of those yet, nor do we plan to)
327 groupData
.type
=== 'single_option' &&
328 // and, if there is a validate method and it passes on
330 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
331 // but if that value isn't already in the definition
333 .map( function ( filterData
) {
334 return String( filterData
.name
);
336 .indexOf( String( val
) ) === -1
338 // Add the filter information
339 groupData
.filters
.push( controller
._createFilterDataFromNumber(
341 groupData
.numToLabelFunc
?
342 groupData
.numToLabelFunc( val
) :
346 // If there's a sort function set up, re-sort the values
347 if ( groupData
.sortFunc
) {
348 groupData
.filters
.sort( groupData
.sortFunc
);
355 * Switch the view of the filters model
357 * @param {string} view Requested view
359 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
360 this.filtersModel
.switchView( view
);
364 * Reset to default filters
366 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
367 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
369 this.updateChangesList();
373 * Check whether the default values of the filters are all false.
375 * @return {boolean} Defaults are all false
377 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
378 var defaultFilters
= this.filtersModel
.getFiltersFromParameters( this._getDefaultParams() );
380 this._deleteExcludedValuesFromFilterState( defaultFilters
);
382 // Defaults can change in a session, so we need to do this every time
383 return Object
.keys( defaultFilters
).every( function ( filterName
) {
384 return !defaultFilters
[ filterName
];
389 * Empty all selected filters
391 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
392 var highlightedFilterNames
= this.filtersModel
393 .getHighlightedItems()
394 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
396 this.filtersModel
.emptyAllFilters();
397 this.filtersModel
.clearAllHighlightColors();
398 // Check all filter interactions
399 this.filtersModel
.reassessFilterInteractions();
401 this.updateChangesList();
403 if ( highlightedFilterNames
) {
404 this._trackHighlight( 'clearAll', highlightedFilterNames
);
409 * Update the selected state of a filter
411 * @param {string} filterName Filter name
412 * @param {boolean} [isSelected] Filter selected state
414 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
415 var filterItem
= this.filtersModel
.getItemByName( filterName
);
418 // If no filter was found, break
422 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
424 if ( filterItem
.isSelected() !== isSelected
) {
425 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
427 this.updateChangesList();
429 // Check filter interactions
430 this.filtersModel
.reassessFilterInteractions( filterItem
);
435 * Clear both highlight and selection of a filter
437 * @param {string} filterName Name of the filter item
439 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
440 var filterItem
= this.filtersModel
.getItemByName( filterName
),
441 isHighlighted
= filterItem
.isHighlighted();
443 if ( filterItem
.isSelected() || isHighlighted
) {
444 this.filtersModel
.clearHighlightColor( filterName
);
445 this.filtersModel
.toggleFilterSelected( filterName
, false );
446 this.updateChangesList();
447 this.filtersModel
.reassessFilterInteractions( filterItem
);
449 // Log filter grouping
450 this.trackFilterGroupings( 'removefilter' );
453 if ( isHighlighted
) {
454 this._trackHighlight( 'clear', filterName
);
459 * Toggle the highlight feature on and off
461 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
462 this.filtersModel
.toggleHighlight();
465 if ( this.filtersModel
.isHighlightEnabled() ) {
466 mw
.hook( 'RcFilters.highlight.enable' ).fire();
471 * Toggle the namespaces inverted feature on and off
473 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
474 this.filtersModel
.toggleInvertedNamespaces();
477 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
478 function ( filterItem
) { return filterItem
.isSelected(); }
481 // Only re-fetch results if there are namespace items that are actually selected
482 this.updateChangesList();
487 * Set the highlight color for a filter item
489 * @param {string} filterName Name of the filter item
490 * @param {string} color Selected color
492 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
493 this.filtersModel
.setHighlightColor( filterName
, color
);
495 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
499 * Clear highlight for a filter item
501 * @param {string} filterName Name of the filter item
503 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
504 this.filtersModel
.clearHighlightColor( filterName
);
506 this._trackHighlight( 'clear', filterName
);
510 * Enable or disable live updates.
511 * @param {boolean} enable True to enable, false to disable
513 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
514 this.changesListModel
.toggleLiveUpdate( enable
);
515 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
516 this.updateChangesList( null, this.LIVE_UPDATE
);
521 * Set a timeout for the next live update.
524 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
525 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
529 * Perform a live update.
532 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
533 if ( !this._shouldCheckForNewChanges() ) {
534 // skip this turn and check back later
535 this._scheduleLiveUpdate();
539 this._checkForNewChanges()
540 .then( function ( newChanges
) {
541 if ( !this._shouldCheckForNewChanges() ) {
542 // by the time the response is received,
543 // it may not be appropriate anymore
548 if ( this.changesListModel
.getLiveUpdate() ) {
549 return this.updateChangesList( null, this.LIVE_UPDATE
);
551 this.changesListModel
.setNewChangesExist( true );
555 .always( this._scheduleLiveUpdate
.bind( this ) );
559 * @return {boolean} It's appropriate to check for new changes now
562 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
563 return !document
.hidden
&&
564 !this.filtersModel
.hasConflict() &&
565 !this.changesListModel
.getNewChangesExist() &&
566 !this.updatingChangesList
&&
567 this.changesListModel
.getNextFrom();
571 * Check if new changes, newer than those currently shown, are available
573 * @return {jQuery.Promise} Promise object that resolves with a bool
574 * specifying if there are new changes or not
578 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
581 peek
: 1, // bypasses ChangesList specific UI
582 from: this.changesListModel
.getNextFrom()
584 return this._queryChangesList( 'liveUpdate', params
).then(
586 // no result is 204 with the 'peek' param
587 return data
.status
=== 200;
593 * Show the new changes
595 * @return {jQuery.Promise} Promise object that resolves after
596 * fetching and showing the new changes
598 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
599 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
603 * Save the current model state as a saved query
605 * @param {string} [label] Label of the saved query
606 * @param {boolean} [setAsDefault=false] This query should be set as the default
608 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
610 highlightedItems
= {},
611 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
612 selectedState
= this.filtersModel
.getSelectedState();
614 // Prepare highlights
615 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
616 highlightedItems
[ item
.getName() ] = highlightEnabled
?
617 item
.getHighlightColor() : null;
619 // These are filter states; highlight is stored as boolean
620 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
622 // Delete all excluded filters
623 this._deleteExcludedValuesFromFilterState( selectedState
);
626 queryID
= this.savedQueriesModel
.addNewQuery(
627 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
629 filters
: selectedState
,
630 highlights
: highlightedItems
,
631 invert
: this.filtersModel
.areNamespacesInverted()
635 if ( setAsDefault
) {
636 this.savedQueriesModel
.setDefault( queryID
);
640 this._saveSavedQueries();
644 * Remove a saved query
646 * @param {string} queryID Query id
648 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
649 this.savedQueriesModel
.removeQuery( queryID
);
651 this._saveSavedQueries();
655 * Rename a saved query
657 * @param {string} queryID Query id
658 * @param {string} newLabel New label for the query
660 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
661 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
664 queryItem
.updateLabel( newLabel
);
666 this._saveSavedQueries();
670 * Set a saved query as default
672 * @param {string} queryID Query Id. If null is given, default
675 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
676 this.savedQueriesModel
.setDefault( queryID
);
677 this._saveSavedQueries();
683 * @param {string} queryID Query id
685 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
686 var data
, highlights
,
687 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
688 currentMatchingQuery
= this.findQueryMatchingCurrentState();
693 // If there's already a query, don't reload it
694 // if it's the same as the one that already exists
695 !currentMatchingQuery
||
696 currentMatchingQuery
.getID() !== queryItem
.getID()
699 data
= queryItem
.getData();
700 highlights
= data
.highlights
;
702 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
703 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
705 // Update model state from filters
706 this.filtersModel
.toggleFiltersSelected(
707 // Merge filters with excluded values
708 $.extend( true, {}, data
.filters
, this.filtersModel
.getExcludedFiltersState() )
711 // Update namespace inverted property
712 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
714 // Update highlight state
715 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
716 this.filtersModel
.getItems().forEach( function ( filterItem
) {
717 var color
= highlights
[ filterItem
.getName() ];
719 filterItem
.setHighlightColor( color
);
721 filterItem
.clearHighlightColor();
725 // Check all filter interactions
726 this.filtersModel
.reassessFilterInteractions();
728 this.updateChangesList();
730 // Log filter grouping
731 this.trackFilterGroupings( 'savedfilters' );
736 * Check whether the current filter and highlight state exists
737 * in the saved queries model.
739 * @return {boolean} Query exists
741 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
742 var highlightedItems
= {},
743 selectedState
= this.filtersModel
.getSelectedState();
745 // Prepare highlights of the current query
746 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
747 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
749 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
751 // Remove anything that should be excluded from the saved query
752 // this includes sticky filters and filters marked with 'excludedFromSavedQueries'
753 this._deleteExcludedValuesFromFilterState( selectedState
);
755 return this.savedQueriesModel
.findMatchingQuery(
757 filters
: selectedState
,
758 highlights
: highlightedItems
,
759 invert
: this.filtersModel
.areNamespacesInverted()
765 * Delete sticky filters from given object
767 * @param {Object} filterState Filter state
769 mw
.rcfilters
.Controller
.prototype._deleteExcludedValuesFromFilterState = function ( filterState
) {
770 // Remove excluded filters
771 $.each( this.filtersModel
.getExcludedFiltersState(), function ( filterName
) {
772 delete filterState
[ filterName
];
777 * Get an object representing the base state of parameters
780 * This is meant to make sure that the saved queries that are
781 * in memory are always the same structure as what we would get
782 * by calling the current model's "getSelectedState" and by checking
785 * In cases where a user saved a query when the system had a certain
786 * set of filters, and then a filter was added to the system, we want
787 * to make sure that the stored queries can still be comparable to
788 * the current state, which means that we need the base state for
791 * - Saved queries are stored in "minimal" view (only changed filters
792 * are stored); When we initialize the system, we merge each minimal
793 * query with the base state (using 'getNormalizedFilters') so all
794 * saved queries have the exact same structure as what we would get
795 * by checking the getSelectedState of the filter.
796 * - When we save the queries, we minimize the object to only represent
797 * whatever has actually changed, rather than store the entire
798 * object. To check what actually is different so we can store it,
799 * we need to obtain a base state to compare against, this is
800 * what #_getMinimalFilterList does
802 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
803 var defaultParams
= this.filtersModel
.getDefaultParams(),
804 highlightedItems
= {};
806 // Prepare highlights
807 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
808 highlightedItems
[ item
.getName() ] = null;
810 highlightedItems
.highlight
= false;
812 this.baseFilterState
= {
813 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
814 highlights
: highlightedItems
,
820 * Get an object representing the base filter state of both
821 * filters and highlights. The structure is similar to what we use
822 * to store each query in the saved queries object:
828 * filterName: (string|null)
832 * @return {Object} Object representing the base state of
833 * parameters and highlights
835 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
836 return this.baseFilterState
;
840 * Get an object that holds only the parameters and highlights that have
841 * values different than the base default value.
843 * This is the reverse of the normalization we do initially on loading and
844 * initializing the saved queries model.
846 * @param {Object} valuesObject Object representing the state of both
847 * filters and highlights in its normalized version, to be minimized.
848 * @return {Object} Minimal filters and highlights list
850 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
851 var result
= { filters
: {}, highlights
: {}, invert
: valuesObject
.invert
},
852 baseState
= this._getBaseFilterState();
855 $.each( valuesObject
.filters
, function ( name
, value
) {
856 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
857 result
.filters
[ name
] = value
;
861 $.each( valuesObject
.highlights
, function ( name
, value
) {
862 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
863 result
.highlights
[ name
] = value
;
871 * Save the current state of the saved queries model with all
872 * query item representation in the user settings.
874 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
876 state
= this.savedQueriesModel
.getState(),
879 // Minimize before save
880 $.each( state
.queries
, function ( queryID
, info
) {
881 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
885 stringified
= JSON
.stringify( state
);
887 if ( $.byteLength( stringified
) > 65535 ) {
888 // Sanity check, since the preference can only hold that.
892 // Save the preference
893 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
894 // Update the preference for this session
895 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
899 * Update sticky preferences with current model state
901 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
902 // Update default sticky values with selected, whether they came from
903 // the initial defaults or from the URL value that is being normalized
904 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
905 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
907 // TODO: Make these automatic by having the model go over sticky
908 // items and update their default values automatically
912 * Update the limit default value
914 * param {number} newValue New value
916 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
917 // HACK: Temporarily remove this from being sticky
921 if ( !$.isNumeric( newValue ) ) {
925 newValue = Number( newValue );
927 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
928 // Save the preference
929 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
930 // Update the preference for this session
931 mw.user.options.set( 'rcfilters-rclimit', newValue );
938 * Update the days default value
940 * param {number} newValue New value
942 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
943 // HACK: Temporarily remove this from being sticky
947 if ( !$.isNumeric( newValue ) ) {
951 newValue = Number( newValue );
953 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
954 // Save the preference
955 new mw.Api().saveOption( 'rcdays', newValue );
956 // Update the preference for this session
957 mw.user.options.set( 'rcdays', newValue );
964 * Update the group by page default value
966 * @param {number} newValue New value
968 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
969 if ( !$.isNumeric( newValue
) ) {
973 newValue
= Number( newValue
);
975 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
976 // Save the preference
977 new mw
.Api().saveOption( 'usenewrc', newValue
);
978 // Update the preference for this session
979 mw
.user
.options
.set( 'usenewrc', newValue
);
984 * Synchronize the URL with the current state of the filters
985 * without adding an history entry.
987 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
988 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
992 * Update filter state (selection and highlighting) based
993 * on current URL values.
995 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
996 * list based on the updated model.
998 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
999 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
1001 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
1003 // Update the sticky preferences, in case we received a value
1005 this.updateStickyPreferences();
1007 // Only update and fetch new results if it is requested
1008 if ( fetchChangesList
) {
1009 this.updateChangesList();
1014 * Update the list of changes and notify the model
1016 * @param {Object} [params] Extra parameters to add to the API call
1017 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
1018 * @return {jQuery.Promise} Promise that is resolved when the update is complete
1020 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
1021 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
1023 if ( updateMode
=== this.FILTER_CHANGE
) {
1024 this._updateURL( params
);
1026 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
1027 this.changesListModel
.invalidate();
1029 this.changesListModel
.setNewChangesExist( false );
1030 this.updatingChangesList
= true;
1031 return this._fetchChangesList()
1034 function ( pieces
) {
1035 var $changesListContent
= pieces
.changes
,
1036 $fieldset
= pieces
.fieldset
;
1037 this.changesListModel
.update(
1038 $changesListContent
,
1041 // separator between old and new changes
1042 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
1045 // Do nothing for failure
1047 .always( function () {
1048 this.updatingChangesList
= false;
1053 * Get an object representing the default parameter state, whether
1054 * it is from the model defaults or from the saved queries.
1056 * @return {Object} Default parameters
1058 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
1059 var data
, queryHighlights
,
1061 savedHighlights
= {},
1062 defaultSavedQueryItem
= !mw
.user
.isAnon() && this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
1064 if ( defaultSavedQueryItem
) {
1065 data
= defaultSavedQueryItem
.getData();
1067 queryHighlights
= data
.highlights
|| {};
1068 savedParams
= this.filtersModel
.getParametersFromFilters(
1069 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
1072 // Translate highlights to parameters
1073 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
1074 $.each( queryHighlights
, function ( filterName
, color
) {
1075 if ( filterName
!== 'highlights' ) {
1076 savedHighlights
[ filterName
+ '_color' ] = color
;
1080 return $.extend( true, {}, savedParams
, savedHighlights
, { invert
: String( Number( data
.invert
|| 0 ) ) } );
1083 return this.filtersModel
.getDefaultParams();
1087 * Update the URL of the page to reflect current filters
1089 * This should not be called directly from outside the controller.
1090 * If an action requires changing the URL, it should either use the
1091 * highlighting actions below, or call #updateChangesList which does
1092 * the uri corrections already.
1094 * @param {Object} [params] Extra parameters to add to the API call
1096 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1097 var currentUri
= new mw
.Uri(),
1098 updatedUri
= this._getUpdatedUri();
1100 updatedUri
.extend( params
|| {} );
1103 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1104 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1106 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1111 * Get an updated mw.Uri object based on the model state
1113 * @return {mw.Uri} Updated Uri
1115 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1116 var uri
= new mw
.Uri();
1119 uri
.query
= this.uriProcessor
.minimizeQuery(
1123 // We want to retain unrecognized params
1124 // The uri params from model will override
1125 // any recognized value in the current uri
1126 // query, retain unrecognized params, and
1127 // the result will then be minimized
1129 this.uriProcessor
.getUriParametersFromModel(),
1138 * Query the list of changes from the server for the current filters
1140 * @param {string} counterId Id for this request. To allow concurrent requests
1141 * not to invalidate each other.
1142 * @param {Object} [params={}] Parameters to add to the query
1144 * @return {jQuery.Promise} Promise object resolved with { content, status }
1146 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1147 var uri
= this._getUpdatedUri(),
1148 stickyParams
= this.filtersModel
.getStickyParams(),
1152 params
= params
|| {};
1153 params
.action
= 'render'; // bypasses MW chrome
1155 uri
.extend( params
);
1157 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1158 requestId
= ++this.requestCounter
[ counterId
];
1159 latestRequest = function () {
1160 return requestId
=== this.requestCounter
[ counterId
];
1163 // Sticky parameters override the URL params
1164 // this is to make sure that whether we represent
1165 // the sticky params in the URL or not (they may
1166 // be normalized out) the sticky parameters are
1167 // always being sent to the server with their
1168 // current/default values
1169 uri
.extend( stickyParams
);
1171 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1173 function ( content
, message
, jqXHR
) {
1174 if ( !latestRequest() ) {
1175 return $.Deferred().reject();
1179 status
: jqXHR
.status
1182 // RC returns 404 when there is no results
1183 function ( jqXHR
) {
1184 if ( latestRequest() ) {
1185 return $.Deferred().resolve(
1187 content
: jqXHR
.responseText
,
1188 status
: jqXHR
.status
1197 * Fetch the list of changes from the server for the current filters
1199 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1202 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1203 return this._queryChangesList( 'updateChangesList' )
1206 var $parsed
= $( '<div>' ).append( $( $.parseHTML( data
.content
) ) ),
1209 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1211 fieldset
: $parsed
.find( 'fieldset.cloptions' ).first()
1214 if ( pieces
.changes
.length
=== 0 ) {
1215 pieces
.changes
= 'NO_RESULTS';
1224 * Track usage of highlight feature
1226 * @param {string} action
1227 * @param {Array|Object|string} filters
1229 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1230 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1231 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1233 'event.ChangesListHighlights',
1237 userId
: mw
.user
.getId()
1243 * Track filter grouping usage
1245 * @param {string} action Action taken
1247 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1248 var controller
= this,
1249 rightNow
= new Date().getTime(),
1250 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1251 // Get all current filters
1252 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1253 return item
.getName();
1256 action
= action
|| 'filtermenu';
1258 // Check if these filters were the ones we just logged previously
1259 // (Don't log the same grouping twice, in case the user opens/closes)
1260 // the menu without action, or with the same result
1262 // Only log if the two arrays are different in size
1263 filters
.length
!== this.prevLoggedItems
.length
||
1264 // Or if any filters are not the same as the cached filters
1265 filters
.some( function ( filterName
) {
1266 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1268 // Or if any cached filters are not the same as given filters
1269 this.prevLoggedItems
.some( function ( filterName
) {
1270 return filters
.indexOf( filterName
) === -1;
1273 filters
.forEach( function ( filterName
) {
1275 'event.ChangesListFilterGrouping',
1278 groupIdentifier
: randomIdentifier
,
1280 userId
: mw
.user
.getId()
1285 // Cache the filter names
1286 this.prevLoggedItems
= filters
;
1291 * Mark all changes as seen on Watchlist
1293 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1294 var api
= new mw
.Api();
1295 api
.postWithToken( 'csrf', {
1297 action
: 'setnotificationtimestamp',
1298 entirewatchlist
: true
1299 } ).then( function () {
1300 this.updateChangesList( null, 'markSeen' );
1303 }( mediaWiki
, jQuery
) );