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._scheduleLiveUpdate();
270 * Create filter data from a number, for the filters that are numerical value
272 * @param {Number} num Number
273 * @param {Number} numForDisplay Number for the label
274 * @return {Object} Filter data
276 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
279 label
: mw
.language
.convertNumber( numForDisplay
)
284 * Add an arbitrary values to groups that allow arbitrary values
286 * @param {Object} groupData Group data
287 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
289 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
290 var controller
= this,
291 normalizeWithinRange = function ( range
, val
) {
292 if ( val
< range
.min
) {
293 return range
.min
; // Min
294 } else if ( val
>= range
.max
) {
295 return range
.max
; // Max
300 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
302 // Normalize the arbitrary values and the default value for a range
303 if ( groupData
.range
) {
304 arbitraryValues
= arbitraryValues
.map( function ( val
) {
305 return normalizeWithinRange( groupData
.range
, val
);
308 // Normalize the default, since that's user defined
309 if ( groupData
.default !== undefined ) {
310 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
314 // This is only true for single_option group
315 // We assume these are the only groups that will allow for
316 // arbitrary, since it doesn't make any sense for the other
318 arbitraryValues
.forEach( function ( val
) {
320 // If the group allows for arbitrary data
321 groupData
.allowArbitrary
&&
322 // and it is single_option (or string_options, but we
323 // don't have cases of those yet, nor do we plan to)
324 groupData
.type
=== 'single_option' &&
325 // and, if there is a validate method and it passes on
327 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
328 // but if that value isn't already in the definition
330 .map( function ( filterData
) {
331 return String( filterData
.name
);
333 .indexOf( String( val
) ) === -1
335 // Add the filter information
336 groupData
.filters
.push( controller
._createFilterDataFromNumber(
338 groupData
.numToLabelFunc
?
339 groupData
.numToLabelFunc( val
) :
343 // If there's a sort function set up, re-sort the values
344 if ( groupData
.sortFunc
) {
345 groupData
.filters
.sort( groupData
.sortFunc
);
352 * Switch the view of the filters model
354 * @param {string} view Requested view
356 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
357 this.filtersModel
.switchView( view
);
361 * Reset to default filters
363 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
364 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
366 this.updateChangesList();
370 * Empty all selected filters
372 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
373 var highlightedFilterNames
= this.filtersModel
374 .getHighlightedItems()
375 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
377 this.filtersModel
.emptyAllFilters();
378 this.filtersModel
.clearAllHighlightColors();
379 // Check all filter interactions
380 this.filtersModel
.reassessFilterInteractions();
382 this.updateChangesList();
384 if ( highlightedFilterNames
) {
385 this._trackHighlight( 'clearAll', highlightedFilterNames
);
390 * Update the selected state of a filter
392 * @param {string} filterName Filter name
393 * @param {boolean} [isSelected] Filter selected state
395 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
396 var filterItem
= this.filtersModel
.getItemByName( filterName
);
399 // If no filter was found, break
403 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
405 if ( filterItem
.isSelected() !== isSelected
) {
406 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
408 this.updateChangesList();
410 // Check filter interactions
411 this.filtersModel
.reassessFilterInteractions( filterItem
);
416 * Clear both highlight and selection of a filter
418 * @param {string} filterName Name of the filter item
420 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
421 var filterItem
= this.filtersModel
.getItemByName( filterName
),
422 isHighlighted
= filterItem
.isHighlighted();
424 if ( filterItem
.isSelected() || isHighlighted
) {
425 this.filtersModel
.clearHighlightColor( filterName
);
426 this.filtersModel
.toggleFilterSelected( filterName
, false );
427 this.updateChangesList();
428 this.filtersModel
.reassessFilterInteractions( filterItem
);
430 // Log filter grouping
431 this.trackFilterGroupings( 'removefilter' );
434 if ( isHighlighted
) {
435 this._trackHighlight( 'clear', filterName
);
440 * Toggle the highlight feature on and off
442 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
443 this.filtersModel
.toggleHighlight();
446 if ( this.filtersModel
.isHighlightEnabled() ) {
447 mw
.hook( 'RcFilters.highlight.enable' ).fire();
452 * Toggle the namespaces inverted feature on and off
454 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
455 this.filtersModel
.toggleInvertedNamespaces();
458 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
459 function ( filterItem
) { return filterItem
.isSelected(); }
462 // Only re-fetch results if there are namespace items that are actually selected
463 this.updateChangesList();
468 * Set the highlight color for a filter item
470 * @param {string} filterName Name of the filter item
471 * @param {string} color Selected color
473 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
474 this.filtersModel
.setHighlightColor( filterName
, color
);
476 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
480 * Clear highlight for a filter item
482 * @param {string} filterName Name of the filter item
484 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
485 this.filtersModel
.clearHighlightColor( filterName
);
487 this._trackHighlight( 'clear', filterName
);
491 * Enable or disable live updates.
492 * @param {boolean} enable True to enable, false to disable
494 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
495 this.changesListModel
.toggleLiveUpdate( enable
);
496 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
497 this.updateChangesList( null, this.LIVE_UPDATE
);
502 * Set a timeout for the next live update.
505 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
506 setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
510 * Perform a live update.
513 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
514 if ( !this._shouldCheckForNewChanges() ) {
515 // skip this turn and check back later
516 this._scheduleLiveUpdate();
520 this._checkForNewChanges()
521 .then( function ( data
) {
522 if ( !this._shouldCheckForNewChanges() ) {
523 // by the time the response is received,
524 // it may not be appropriate anymore
528 if ( data
.changes
!== 'NO_RESULTS' ) {
529 if ( this.changesListModel
.getLiveUpdate() ) {
530 return this.updateChangesList( null, this.LIVE_UPDATE
);
532 this.changesListModel
.setNewChangesExist( true );
536 .always( this._scheduleLiveUpdate
.bind( this ) );
540 * @return {boolean} It's appropriate to check for new changes now
543 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
544 return !document
.hidden
&&
545 !this.filtersModel
.hasConflict() &&
546 !this.changesListModel
.getNewChangesExist() &&
547 !this.updatingChangesList
&&
548 this.changesListModel
.getNextFrom();
552 * Check if new changes, newer than those currently shown, are available
554 * @return {jQuery.Promise} Promise object that resolves after trying
555 * to fetch 1 change newer than the last known 'from' parameter value
559 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
560 return this._fetchChangesList(
564 // temporarily disabled ( T173613#3591657 )
565 // peek: 1, // bypasses all UI
566 from: this.changesListModel
.getNextFrom()
572 * Show the new changes
574 * @return {jQuery.Promise} Promise object that resolves after
575 * fetching and showing the new changes
577 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
578 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
582 * Save the current model state as a saved query
584 * @param {string} [label] Label of the saved query
585 * @param {boolean} [setAsDefault=false] This query should be set as the default
587 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
589 highlightedItems
= {},
590 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
591 selectedState
= this.filtersModel
.getSelectedState();
593 // Prepare highlights
594 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
595 highlightedItems
[ item
.getName() ] = highlightEnabled
?
596 item
.getHighlightColor() : null;
598 // These are filter states; highlight is stored as boolean
599 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
601 // Delete all excluded filters
602 this._deleteExcludedValuesFromFilterState( selectedState
);
605 queryID
= this.savedQueriesModel
.addNewQuery(
606 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
608 filters
: selectedState
,
609 highlights
: highlightedItems
,
610 invert
: this.filtersModel
.areNamespacesInverted()
614 if ( setAsDefault
) {
615 this.savedQueriesModel
.setDefault( queryID
);
619 this._saveSavedQueries();
623 * Remove a saved query
625 * @param {string} queryID Query id
627 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
628 this.savedQueriesModel
.removeQuery( queryID
);
630 this._saveSavedQueries();
634 * Rename a saved query
636 * @param {string} queryID Query id
637 * @param {string} newLabel New label for the query
639 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
640 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
643 queryItem
.updateLabel( newLabel
);
645 this._saveSavedQueries();
649 * Set a saved query as default
651 * @param {string} queryID Query Id. If null is given, default
654 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
655 this.savedQueriesModel
.setDefault( queryID
);
656 this._saveSavedQueries();
662 * @param {string} queryID Query id
664 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
665 var data
, highlights
,
666 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
667 currentMatchingQuery
= this.findQueryMatchingCurrentState();
672 // If there's already a query, don't reload it
673 // if it's the same as the one that already exists
674 !currentMatchingQuery
||
675 currentMatchingQuery
.getID() !== queryItem
.getID()
678 data
= queryItem
.getData();
679 highlights
= data
.highlights
;
681 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
682 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
684 // Update model state from filters
685 this.filtersModel
.toggleFiltersSelected(
686 // Merge filters with excluded values
687 $.extend( true, {}, data
.filters
, this.filtersModel
.getExcludedFiltersState() )
690 // Update namespace inverted property
691 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
693 // Update highlight state
694 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
695 this.filtersModel
.getItems().forEach( function ( filterItem
) {
696 var color
= highlights
[ filterItem
.getName() ];
698 filterItem
.setHighlightColor( color
);
700 filterItem
.clearHighlightColor();
704 // Check all filter interactions
705 this.filtersModel
.reassessFilterInteractions();
707 this.updateChangesList();
709 // Log filter grouping
710 this.trackFilterGroupings( 'savedfilters' );
715 * Check whether the current filter and highlight state exists
716 * in the saved queries model.
718 * @return {boolean} Query exists
720 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
721 var highlightedItems
= {},
722 selectedState
= this.filtersModel
.getSelectedState();
724 // Prepare highlights of the current query
725 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
726 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
728 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
730 // Remove anything that should be excluded from the saved query
731 // this includes sticky filters and filters marked with 'excludedFromSavedQueries'
732 this._deleteExcludedValuesFromFilterState( selectedState
);
734 return this.savedQueriesModel
.findMatchingQuery(
736 filters
: selectedState
,
737 highlights
: highlightedItems
,
738 invert
: this.filtersModel
.areNamespacesInverted()
744 * Delete sticky filters from given object
746 * @param {Object} filterState Filter state
748 mw
.rcfilters
.Controller
.prototype._deleteExcludedValuesFromFilterState = function ( filterState
) {
749 // Remove excluded filters
750 $.each( this.filtersModel
.getExcludedFiltersState(), function ( filterName
) {
751 delete filterState
[ filterName
];
756 * Get an object representing the base state of parameters
759 * This is meant to make sure that the saved queries that are
760 * in memory are always the same structure as what we would get
761 * by calling the current model's "getSelectedState" and by checking
764 * In cases where a user saved a query when the system had a certain
765 * set of filters, and then a filter was added to the system, we want
766 * to make sure that the stored queries can still be comparable to
767 * the current state, which means that we need the base state for
770 * - Saved queries are stored in "minimal" view (only changed filters
771 * are stored); When we initialize the system, we merge each minimal
772 * query with the base state (using 'getNormalizedFilters') so all
773 * saved queries have the exact same structure as what we would get
774 * by checking the getSelectedState of the filter.
775 * - When we save the queries, we minimize the object to only represent
776 * whatever has actually changed, rather than store the entire
777 * object. To check what actually is different so we can store it,
778 * we need to obtain a base state to compare against, this is
779 * what #_getMinimalFilterList does
781 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
782 var defaultParams
= this.filtersModel
.getDefaultParams(),
783 highlightedItems
= {};
785 // Prepare highlights
786 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
787 highlightedItems
[ item
.getName() ] = null;
789 highlightedItems
.highlight
= false;
791 this.baseFilterState
= {
792 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
793 highlights
: highlightedItems
,
799 * Get an object representing the base filter state of both
800 * filters and highlights. The structure is similar to what we use
801 * to store each query in the saved queries object:
807 * filterName: (string|null)
811 * @return {Object} Object representing the base state of
812 * parameters and highlights
814 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
815 return this.baseFilterState
;
819 * Get an object that holds only the parameters and highlights that have
820 * values different than the base default value.
822 * This is the reverse of the normalization we do initially on loading and
823 * initializing the saved queries model.
825 * @param {Object} valuesObject Object representing the state of both
826 * filters and highlights in its normalized version, to be minimized.
827 * @return {Object} Minimal filters and highlights list
829 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
830 var result
= { filters
: {}, highlights
: {}, invert
: valuesObject
.invert
},
831 baseState
= this._getBaseFilterState();
834 $.each( valuesObject
.filters
, function ( name
, value
) {
835 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
836 result
.filters
[ name
] = value
;
840 $.each( valuesObject
.highlights
, function ( name
, value
) {
841 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
842 result
.highlights
[ name
] = value
;
850 * Save the current state of the saved queries model with all
851 * query item representation in the user settings.
853 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
855 state
= this.savedQueriesModel
.getState(),
858 // Minimize before save
859 $.each( state
.queries
, function ( queryID
, info
) {
860 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
864 stringified
= JSON
.stringify( state
);
866 if ( stringified
.length
> 65535 ) {
867 // Sanity check, since the preference can only hold that.
871 // Save the preference
872 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
873 // Update the preference for this session
874 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
878 * Update sticky preferences with current model state
880 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
881 // Update default sticky values with selected, whether they came from
882 // the initial defaults or from the URL value that is being normalized
883 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
884 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
886 // TODO: Make these automatic by having the model go over sticky
887 // items and update their default values automatically
891 * Update the limit default value
893 * param {number} newValue New value
895 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
896 // HACK: Temporarily remove this from being sticky
900 if ( !$.isNumeric( newValue ) ) {
904 newValue = Number( newValue );
906 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
907 // Save the preference
908 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
909 // Update the preference for this session
910 mw.user.options.set( 'rcfilters-rclimit', newValue );
917 * Update the days default value
919 * param {number} newValue New value
921 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
922 // HACK: Temporarily remove this from being sticky
926 if ( !$.isNumeric( newValue ) ) {
930 newValue = Number( newValue );
932 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
933 // Save the preference
934 new mw.Api().saveOption( 'rcdays', newValue );
935 // Update the preference for this session
936 mw.user.options.set( 'rcdays', newValue );
943 * Update the group by page default value
945 * @param {number} newValue New value
947 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
948 if ( !$.isNumeric( newValue
) ) {
952 newValue
= Number( newValue
);
954 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
955 // Save the preference
956 new mw
.Api().saveOption( 'usenewrc', newValue
);
957 // Update the preference for this session
958 mw
.user
.options
.set( 'usenewrc', newValue
);
963 * Synchronize the URL with the current state of the filters
964 * without adding an history entry.
966 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
967 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
971 * Update filter state (selection and highlighting) based
972 * on current URL values.
974 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
975 * list based on the updated model.
977 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
978 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
980 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
982 // Update the sticky preferences, in case we received a value
984 this.updateStickyPreferences();
986 // Only update and fetch new results if it is requested
987 if ( fetchChangesList
) {
988 this.updateChangesList();
993 * Update the list of changes and notify the model
995 * @param {Object} [params] Extra parameters to add to the API call
996 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
997 * @return {jQuery.Promise} Promise that is resolved when the update is complete
999 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
1000 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
1002 if ( updateMode
=== this.FILTER_CHANGE
) {
1003 this._updateURL( params
);
1005 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
1006 this.changesListModel
.invalidate();
1008 this.changesListModel
.setNewChangesExist( false );
1009 this.updatingChangesList
= true;
1010 return this._fetchChangesList()
1013 function ( pieces
) {
1014 var $changesListContent
= pieces
.changes
,
1015 $fieldset
= pieces
.fieldset
;
1016 this.changesListModel
.update(
1017 $changesListContent
,
1020 // separator between old and new changes
1021 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
1024 // Do nothing for failure
1026 .always( function () {
1027 this.updatingChangesList
= false;
1032 * Get an object representing the default parameter state, whether
1033 * it is from the model defaults or from the saved queries.
1035 * @return {Object} Default parameters
1037 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
1038 var data
, queryHighlights
,
1040 savedHighlights
= {},
1041 defaultSavedQueryItem
= !mw
.user
.isAnon() && this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
1043 if ( defaultSavedQueryItem
) {
1044 data
= defaultSavedQueryItem
.getData();
1046 queryHighlights
= data
.highlights
|| {};
1047 savedParams
= this.filtersModel
.getParametersFromFilters(
1048 // Merge filters with sticky values
1049 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
1052 // Translate highlights to parameters
1053 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
1054 $.each( queryHighlights
, function ( filterName
, color
) {
1055 if ( filterName
!== 'highlights' ) {
1056 savedHighlights
[ filterName
+ '_color' ] = color
;
1060 return $.extend( true, {}, savedParams
, savedHighlights
, { invert
: String( Number( data
.invert
|| 0 ) ) } );
1063 return this.filtersModel
.getDefaultParams();
1067 * Update the URL of the page to reflect current filters
1069 * This should not be called directly from outside the controller.
1070 * If an action requires changing the URL, it should either use the
1071 * highlighting actions below, or call #updateChangesList which does
1072 * the uri corrections already.
1074 * @param {Object} [params] Extra parameters to add to the API call
1076 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1077 var currentUri
= new mw
.Uri(),
1078 updatedUri
= this._getUpdatedUri();
1080 updatedUri
.extend( params
|| {} );
1083 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1084 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1086 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1091 * Get an updated mw.Uri object based on the model state
1093 * @return {mw.Uri} Updated Uri
1095 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1096 var uri
= new mw
.Uri();
1099 uri
.query
= this.uriProcessor
.minimizeQuery(
1103 // We want to retain unrecognized params
1104 // The uri params from model will override
1105 // any recognized value in the current uri
1106 // query, retain unrecognized params, and
1107 // the result will then be minimized
1109 this.uriProcessor
.getUriParametersFromModel(),
1118 * Fetch the list of changes from the server for the current filters
1120 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1121 * not to invalidate each other.
1122 * @param {Object} [params={}] Parameters to add to the query
1124 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1125 * or with a string denoting no results.
1127 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function ( counterId
, params
) {
1128 var uri
= this._getUpdatedUri(),
1129 stickyParams
= this.filtersModel
.getStickyParams(),
1133 counterId
= counterId
|| 'updateChangesList';
1134 params
= params
|| {};
1135 params
.action
= 'render'; // bypasses MW chrome
1137 uri
.extend( params
);
1139 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1140 requestId
= ++this.requestCounter
[ counterId
];
1141 latestRequest = function () {
1142 return requestId
=== this.requestCounter
[ counterId
];
1145 // Sticky parameters override the URL params
1146 // this is to make sure that whether we represent
1147 // the sticky params in the URL or not (they may
1148 // be normalized out) the sticky parameters are
1149 // always being sent to the server with their
1150 // current/default values
1151 uri
.extend( stickyParams
);
1153 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1155 function ( html
, reason
) {
1159 if ( !latestRequest() ) {
1160 return $.Deferred().reject();
1163 if ( params
.peek
&& reason
=== 'notmodified' ) {
1165 changes
: 'NO_RESULTS'
1169 // Because of action=render, the response is a list of nodes.
1170 // It has to be put under a root node so it can be queried.
1171 $parsed
= $( '<div>' ).append( $( $.parseHTML( html
) ) );
1175 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1177 fieldset
: $parsed
.find( 'fieldset.cloptions' ).first()
1180 // Watchlist returns 200 when there is no results
1181 if ( pieces
.changes
.length
=== 0 ) {
1182 pieces
.changes
= 'NO_RESULTS';
1187 // RC returns 404 when there is no results
1188 function ( responseObj
) {
1191 if ( !latestRequest() ) {
1192 return $.Deferred().reject();
1195 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
1197 // Force a resolve state to this promise
1198 return $.Deferred().resolve( {
1199 changes
: 'NO_RESULTS',
1200 fieldset
: $parsed
.find( 'fieldset.cloptions' ).first()
1207 * Track usage of highlight feature
1209 * @param {string} action
1210 * @param {Array|Object|string} filters
1212 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1213 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1214 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1216 'event.ChangesListHighlights',
1220 userId
: mw
.user
.getId()
1226 * Track filter grouping usage
1228 * @param {string} action Action taken
1230 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1231 var controller
= this,
1232 rightNow
= new Date().getTime(),
1233 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1234 // Get all current filters
1235 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1236 return item
.getName();
1239 action
= action
|| 'filtermenu';
1241 // Check if these filters were the ones we just logged previously
1242 // (Don't log the same grouping twice, in case the user opens/closes)
1243 // the menu without action, or with the same result
1245 // Only log if the two arrays are different in size
1246 filters
.length
!== this.prevLoggedItems
.length
||
1247 // Or if any filters are not the same as the cached filters
1248 filters
.some( function ( filterName
) {
1249 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1251 // Or if any cached filters are not the same as given filters
1252 this.prevLoggedItems
.some( function ( filterName
) {
1253 return filters
.indexOf( filterName
) === -1;
1256 filters
.forEach( function ( filterName
) {
1258 'event.ChangesListFilterGrouping',
1261 groupIdentifier
: randomIdentifier
,
1263 userId
: mw
.user
.getId()
1268 // Cache the filter names
1269 this.prevLoggedItems
= filters
;
1274 * Mark all changes as seen on Watchlist
1276 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1277 var api
= new mw
.Api();
1278 api
.postWithToken( 'csrf', {
1280 action
: 'setnotificationtimestamp',
1281 entirewatchlist
: true
1282 } ).then( function () {
1283 this.updateChangesList( null, 'markSeen' );
1286 }( mediaWiki
, jQuery
) );