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
, limitDefault
,
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 // Convert the default from the old preference
101 // since the limit preference actually affects more
102 // than just the RecentChanges page
103 limitDefault
= Number( mw
.user
.options
.get( 'rclimit', '50' ) );
105 // Add parameter range operations
110 type
: 'single_option',
111 title
: '', // Because it's a hidden group, this title actually appears nowhere
113 allowArbitrary
: true,
114 validate
: $.isNumeric
,
116 min
: 0, // The server normalizes negative numbers to 0 results
119 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
120 'default': String( limitDefault
),
121 // Temporarily making this not sticky until we resolve the problem
122 // with the misleading preference. Note that if this is to be permanent
123 // we should remove all sticky behavior methods completely
126 excludedFromSavedQueries
: true,
127 filters
: displayConfig
.limitArray
.map( function ( num
) {
128 return controller
._createFilterDataFromNumber( num
, num
);
133 type
: 'single_option',
134 title
: '', // Because it's a hidden group, this title actually appears nowhere
136 allowArbitrary
: true,
137 validate
: $.isNumeric
,
140 max
: displayConfig
.maxDays
142 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
143 numToLabelFunc: function ( i
) {
144 return Number( i
) < 1 ?
145 ( Number( i
) * 24 ).toFixed( 2 ) :
148 'default': mw
.user
.options
.get( 'rcdays', '30' ),
149 // Temporarily making this not sticky while limit is not sticky, see above
151 excludedFromSavedQueries
: true,
153 // Hours (1, 2, 6, 12)
154 0.04166, 0.0833, 0.25, 0.5
156 ].concat( displayConfig
.daysArray
)
157 .map( function ( num
) {
158 return controller
._createFilterDataFromNumber(
160 // Convert fractions of days to number of hours for the labels
161 num
< 1 ? Math
.round( num
* 24 ) : num
173 title
: '', // Because it's a hidden group, this title actually appears nowhere
179 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
186 // Before we do anything, we need to see if we require additional items in the
187 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
188 // groups; if we ever expand it, this might need further generalization:
189 $.each( views
, function ( viewName
, viewData
) {
190 viewData
.groups
.forEach( function ( groupData
) {
191 var extraValues
= [];
192 if ( groupData
.allowArbitrary
) {
193 // If the value in the URI isn't in the group, add it
194 if ( uri
.query
[ groupData
.name
] !== undefined ) {
195 extraValues
.push( uri
.query
[ groupData
.name
] );
197 // If the default value isn't in the group, add it
198 if ( groupData
.default !== undefined ) {
199 extraValues
.push( String( groupData
.default ) );
201 controller
.addNumberValuesToGroup( groupData
, extraValues
);
206 // Initialize the model
207 this.filtersModel
.initializeFilters( filterStructure
, views
);
209 this._buildBaseFilterState();
211 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
215 if ( !mw
.user
.isAnon() ) {
217 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
219 parsedSavedQueries
= {};
222 // The queries are saved in a minimized state, so we need
223 // to send over the base state so the saved queries model
224 // can normalize them per each query item
225 this.savedQueriesModel
.initialize(
227 this._getBaseFilterState(),
228 // This is for backwards compatibility - delete all excluded filter states
229 Object
.keys( this.filtersModel
.getExcludedFiltersState() )
233 // Check whether we need to load defaults.
234 // We do this by checking whether the current URI query
235 // contains any parameters recognized by the system.
236 // If it does, we load the given state.
237 // If it doesn't, we have no values at all, and we assume
238 // the user loads the base-page and we load defaults.
239 // Defaults should only be applied on load (if necessary)
241 this.initializing
= true;
243 !mw
.user
.isAnon() && this.savedQueriesModel
.getDefault() &&
244 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
246 // We have defaults from a saved query.
247 // We will load them straight-forward (as if
248 // they were clicked in the menu) so we trigger
249 // a full ajax request and change of URL
250 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
252 // There are either recognized parameters in the URL
253 // or there are none, but there is also no default
254 // saved query (so defaults are from the backend)
255 // We want to update the state but not fetch results
257 this.updateStateFromUrl( false );
259 // Update the changes list with the existing data
260 // so it gets processed
261 this.changesListModel
.update(
262 $changesList
.length
? $changesList
: 'NO_RESULTS',
263 $( 'fieldset.cloptions' ).first(),
264 true // We're using existing DOM elements
268 this.initializing
= false;
269 this.switchView( 'default' );
271 this._scheduleLiveUpdate();
275 * Create filter data from a number, for the filters that are numerical value
277 * @param {Number} num Number
278 * @param {Number} numForDisplay Number for the label
279 * @return {Object} Filter data
281 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
284 label
: mw
.language
.convertNumber( numForDisplay
)
289 * Add an arbitrary values to groups that allow arbitrary values
291 * @param {Object} groupData Group data
292 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
294 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
295 var controller
= this,
296 normalizeWithinRange = function ( range
, val
) {
297 if ( val
< range
.min
) {
298 return range
.min
; // Min
299 } else if ( val
>= range
.max
) {
300 return range
.max
; // Max
305 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
307 // Normalize the arbitrary values and the default value for a range
308 if ( groupData
.range
) {
309 arbitraryValues
= arbitraryValues
.map( function ( val
) {
310 return normalizeWithinRange( groupData
.range
, val
);
313 // Normalize the default, since that's user defined
314 if ( groupData
.default !== undefined ) {
315 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
319 // This is only true for single_option group
320 // We assume these are the only groups that will allow for
321 // arbitrary, since it doesn't make any sense for the other
323 arbitraryValues
.forEach( function ( val
) {
325 // If the group allows for arbitrary data
326 groupData
.allowArbitrary
&&
327 // and it is single_option (or string_options, but we
328 // don't have cases of those yet, nor do we plan to)
329 groupData
.type
=== 'single_option' &&
330 // and, if there is a validate method and it passes on
332 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
333 // but if that value isn't already in the definition
335 .map( function ( filterData
) {
336 return String( filterData
.name
);
338 .indexOf( String( val
) ) === -1
340 // Add the filter information
341 groupData
.filters
.push( controller
._createFilterDataFromNumber(
343 groupData
.numToLabelFunc
?
344 groupData
.numToLabelFunc( val
) :
348 // If there's a sort function set up, re-sort the values
349 if ( groupData
.sortFunc
) {
350 groupData
.filters
.sort( groupData
.sortFunc
);
357 * Switch the view of the filters model
359 * @param {string} view Requested view
361 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
362 this.filtersModel
.switchView( view
);
366 * Reset to default filters
368 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
369 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
371 this.updateChangesList();
375 * Empty all selected filters
377 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
378 var highlightedFilterNames
= this.filtersModel
379 .getHighlightedItems()
380 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
382 this.filtersModel
.emptyAllFilters();
383 this.filtersModel
.clearAllHighlightColors();
384 // Check all filter interactions
385 this.filtersModel
.reassessFilterInteractions();
387 this.updateChangesList();
389 if ( highlightedFilterNames
) {
390 this._trackHighlight( 'clearAll', highlightedFilterNames
);
395 * Update the selected state of a filter
397 * @param {string} filterName Filter name
398 * @param {boolean} [isSelected] Filter selected state
400 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
401 var filterItem
= this.filtersModel
.getItemByName( filterName
);
404 // If no filter was found, break
408 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
410 if ( filterItem
.isSelected() !== isSelected
) {
411 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
413 this.updateChangesList();
415 // Check filter interactions
416 this.filtersModel
.reassessFilterInteractions( filterItem
);
421 * Clear both highlight and selection of a filter
423 * @param {string} filterName Name of the filter item
425 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
426 var filterItem
= this.filtersModel
.getItemByName( filterName
),
427 isHighlighted
= filterItem
.isHighlighted();
429 if ( filterItem
.isSelected() || isHighlighted
) {
430 this.filtersModel
.clearHighlightColor( filterName
);
431 this.filtersModel
.toggleFilterSelected( filterName
, false );
432 this.updateChangesList();
433 this.filtersModel
.reassessFilterInteractions( filterItem
);
435 // Log filter grouping
436 this.trackFilterGroupings( 'removefilter' );
439 if ( isHighlighted
) {
440 this._trackHighlight( 'clear', filterName
);
445 * Toggle the highlight feature on and off
447 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
448 this.filtersModel
.toggleHighlight();
451 if ( this.filtersModel
.isHighlightEnabled() ) {
452 mw
.hook( 'RcFilters.highlight.enable' ).fire();
457 * Toggle the namespaces inverted feature on and off
459 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
460 this.filtersModel
.toggleInvertedNamespaces();
463 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
464 function ( filterItem
) { return filterItem
.isSelected(); }
467 // Only re-fetch results if there are namespace items that are actually selected
468 this.updateChangesList();
473 * Set the highlight color for a filter item
475 * @param {string} filterName Name of the filter item
476 * @param {string} color Selected color
478 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
479 this.filtersModel
.setHighlightColor( filterName
, color
);
481 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
485 * Clear highlight for a filter item
487 * @param {string} filterName Name of the filter item
489 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
490 this.filtersModel
.clearHighlightColor( filterName
);
492 this._trackHighlight( 'clear', filterName
);
496 * Enable or disable live updates.
497 * @param {boolean} enable True to enable, false to disable
499 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
500 this.changesListModel
.toggleLiveUpdate( enable
);
501 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
502 this.updateChangesList( null, this.LIVE_UPDATE
);
507 * Set a timeout for the next live update.
510 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
511 setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
515 * Perform a live update.
518 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
519 if ( !this._shouldCheckForNewChanges() ) {
520 // skip this turn and check back later
521 this._scheduleLiveUpdate();
525 this._checkForNewChanges()
526 .then( function ( data
) {
527 if ( !this._shouldCheckForNewChanges() ) {
528 // by the time the response is received,
529 // it may not be appropriate anymore
533 if ( data
.changes
!== 'NO_RESULTS' ) {
534 if ( this.changesListModel
.getLiveUpdate() ) {
535 return this.updateChangesList( null, this.LIVE_UPDATE
);
537 this.changesListModel
.setNewChangesExist( true );
541 .always( this._scheduleLiveUpdate
.bind( this ) );
545 * @return {boolean} It's appropriate to check for new changes now
548 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
549 return !document
.hidden
&&
550 !this.filtersModel
.hasConflict() &&
551 !this.changesListModel
.getNewChangesExist() &&
552 !this.updatingChangesList
&&
553 this.changesListModel
.getNextFrom();
557 * Check if new changes, newer than those currently shown, are available
559 * @return {jQuery.Promise} Promise object that resolves after trying
560 * to fetch 1 change newer than the last known 'from' parameter value
564 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
565 return this._fetchChangesList(
569 from: this.changesListModel
.getNextFrom()
575 * Show the new changes
577 * @return {jQuery.Promise} Promise object that resolves after
578 * fetching and showing the new changes
580 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
581 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
585 * Save the current model state as a saved query
587 * @param {string} [label] Label of the saved query
588 * @param {boolean} [setAsDefault=false] This query should be set as the default
590 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
592 highlightedItems
= {},
593 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
594 selectedState
= this.filtersModel
.getSelectedState();
596 // Prepare highlights
597 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
598 highlightedItems
[ item
.getName() ] = highlightEnabled
?
599 item
.getHighlightColor() : null;
601 // These are filter states; highlight is stored as boolean
602 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
604 // Delete all excluded filters
605 this._deleteExcludedValuesFromFilterState( selectedState
);
608 queryID
= this.savedQueriesModel
.addNewQuery(
609 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
611 filters
: selectedState
,
612 highlights
: highlightedItems
,
613 invert
: this.filtersModel
.areNamespacesInverted()
617 if ( setAsDefault
) {
618 this.savedQueriesModel
.setDefault( queryID
);
622 this._saveSavedQueries();
626 * Remove a saved query
628 * @param {string} queryID Query id
630 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
631 this.savedQueriesModel
.removeQuery( queryID
);
633 this._saveSavedQueries();
637 * Rename a saved query
639 * @param {string} queryID Query id
640 * @param {string} newLabel New label for the query
642 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
643 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
646 queryItem
.updateLabel( newLabel
);
648 this._saveSavedQueries();
652 * Set a saved query as default
654 * @param {string} queryID Query Id. If null is given, default
657 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
658 this.savedQueriesModel
.setDefault( queryID
);
659 this._saveSavedQueries();
665 * @param {string} queryID Query id
667 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
668 var data
, highlights
,
669 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
670 currentMatchingQuery
= this.findQueryMatchingCurrentState();
675 // If there's already a query, don't reload it
676 // if it's the same as the one that already exists
677 !currentMatchingQuery
||
678 currentMatchingQuery
.getID() !== queryItem
.getID()
681 data
= queryItem
.getData();
682 highlights
= data
.highlights
;
684 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
685 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
687 // Update model state from filters
688 this.filtersModel
.toggleFiltersSelected(
689 // Merge filters with excluded values
690 $.extend( true, {}, data
.filters
, this.filtersModel
.getExcludedFiltersState() )
693 // Update namespace inverted property
694 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
696 // Update highlight state
697 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
698 this.filtersModel
.getItems().forEach( function ( filterItem
) {
699 var color
= highlights
[ filterItem
.getName() ];
701 filterItem
.setHighlightColor( color
);
703 filterItem
.clearHighlightColor();
707 // Check all filter interactions
708 this.filtersModel
.reassessFilterInteractions();
710 this.updateChangesList();
712 // Log filter grouping
713 this.trackFilterGroupings( 'savedfilters' );
718 * Check whether the current filter and highlight state exists
719 * in the saved queries model.
721 * @return {boolean} Query exists
723 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
724 var highlightedItems
= {},
725 selectedState
= this.filtersModel
.getSelectedState();
727 // Prepare highlights of the current query
728 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
729 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
731 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
733 // Remove anything that should be excluded from the saved query
734 // this includes sticky filters and filters marked with 'excludedFromSavedQueries'
735 this._deleteExcludedValuesFromFilterState( selectedState
);
737 return this.savedQueriesModel
.findMatchingQuery(
739 filters
: selectedState
,
740 highlights
: highlightedItems
,
741 invert
: this.filtersModel
.areNamespacesInverted()
747 * Delete sticky filters from given object
749 * @param {Object} filterState Filter state
751 mw
.rcfilters
.Controller
.prototype._deleteExcludedValuesFromFilterState = function ( filterState
) {
752 // Remove excluded filters
753 $.each( this.filtersModel
.getExcludedFiltersState(), function ( filterName
) {
754 delete filterState
[ filterName
];
759 * Get an object representing the base state of parameters
762 * This is meant to make sure that the saved queries that are
763 * in memory are always the same structure as what we would get
764 * by calling the current model's "getSelectedState" and by checking
767 * In cases where a user saved a query when the system had a certain
768 * set of filters, and then a filter was added to the system, we want
769 * to make sure that the stored queries can still be comparable to
770 * the current state, which means that we need the base state for
773 * - Saved queries are stored in "minimal" view (only changed filters
774 * are stored); When we initialize the system, we merge each minimal
775 * query with the base state (using 'getNormalizedFilters') so all
776 * saved queries have the exact same structure as what we would get
777 * by checking the getSelectedState of the filter.
778 * - When we save the queries, we minimize the object to only represent
779 * whatever has actually changed, rather than store the entire
780 * object. To check what actually is different so we can store it,
781 * we need to obtain a base state to compare against, this is
782 * what #_getMinimalFilterList does
784 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
785 var defaultParams
= this.filtersModel
.getDefaultParams(),
786 highlightedItems
= {};
788 // Prepare highlights
789 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
790 highlightedItems
[ item
.getName() ] = null;
792 highlightedItems
.highlight
= false;
794 this.baseFilterState
= {
795 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
796 highlights
: highlightedItems
,
802 * Get an object representing the base filter state of both
803 * filters and highlights. The structure is similar to what we use
804 * to store each query in the saved queries object:
810 * filterName: (string|null)
814 * @return {Object} Object representing the base state of
815 * parameters and highlights
817 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
818 return this.baseFilterState
;
822 * Get an object that holds only the parameters and highlights that have
823 * values different than the base default value.
825 * This is the reverse of the normalization we do initially on loading and
826 * initializing the saved queries model.
828 * @param {Object} valuesObject Object representing the state of both
829 * filters and highlights in its normalized version, to be minimized.
830 * @return {Object} Minimal filters and highlights list
832 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
833 var result
= { filters
: {}, highlights
: {}, invert
: valuesObject
.invert
},
834 baseState
= this._getBaseFilterState();
837 $.each( valuesObject
.filters
, function ( name
, value
) {
838 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
839 result
.filters
[ name
] = value
;
843 $.each( valuesObject
.highlights
, function ( name
, value
) {
844 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
845 result
.highlights
[ name
] = value
;
853 * Save the current state of the saved queries model with all
854 * query item representation in the user settings.
856 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
858 state
= this.savedQueriesModel
.getState(),
861 // Minimize before save
862 $.each( state
.queries
, function ( queryID
, info
) {
863 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
867 stringified
= JSON
.stringify( state
);
869 if ( stringified
.length
> 65535 ) {
870 // Sanity check, since the preference can only hold that.
874 // Save the preference
875 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
876 // Update the preference for this session
877 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
881 * Update sticky preferences with current model state
883 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
884 // Update default sticky values with selected, whether they came from
885 // the initial defaults or from the URL value that is being normalized
886 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
887 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
889 // TODO: Make these automatic by having the model go over sticky
890 // items and update their default values automatically
894 * Update the limit default value
896 * param {number} newValue New value
898 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
899 // HACK: Temporarily remove this from being sticky
903 if ( !$.isNumeric( newValue ) ) {
907 newValue = Number( newValue );
909 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
910 // Save the preference
911 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
912 // Update the preference for this session
913 mw.user.options.set( 'rcfilters-rclimit', newValue );
920 * Update the days default value
922 * param {number} newValue New value
924 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
925 // HACK: Temporarily remove this from being sticky
929 if ( !$.isNumeric( newValue ) ) {
933 newValue = Number( newValue );
935 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
936 // Save the preference
937 new mw.Api().saveOption( 'rcdays', newValue );
938 // Update the preference for this session
939 mw.user.options.set( 'rcdays', newValue );
946 * Update the group by page default value
948 * @param {number} newValue New value
950 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
951 if ( !$.isNumeric( newValue
) ) {
955 newValue
= Number( newValue
);
957 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
958 // Save the preference
959 new mw
.Api().saveOption( 'usenewrc', newValue
);
960 // Update the preference for this session
961 mw
.user
.options
.set( 'usenewrc', newValue
);
966 * Synchronize the URL with the current state of the filters
967 * without adding an history entry.
969 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
970 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
974 * Update filter state (selection and highlighting) based
975 * on current URL values.
977 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
978 * list based on the updated model.
980 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
981 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
983 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
985 // Update the sticky preferences, in case we received a value
987 this.updateStickyPreferences();
989 // Only update and fetch new results if it is requested
990 if ( fetchChangesList
) {
991 this.updateChangesList();
996 * Update the list of changes and notify the model
998 * @param {Object} [params] Extra parameters to add to the API call
999 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
1000 * @return {jQuery.Promise} Promise that is resolved when the update is complete
1002 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
1003 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
1005 if ( updateMode
=== this.FILTER_CHANGE
) {
1006 this._updateURL( params
);
1008 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
1009 this.changesListModel
.invalidate();
1011 this.changesListModel
.setNewChangesExist( false );
1012 this.updatingChangesList
= true;
1013 return this._fetchChangesList()
1016 function ( pieces
) {
1017 var $changesListContent
= pieces
.changes
,
1018 $fieldset
= pieces
.fieldset
;
1019 this.changesListModel
.update(
1020 $changesListContent
,
1023 // separator between old and new changes
1024 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
1027 // Do nothing for failure
1029 .always( function () {
1030 this.updatingChangesList
= false;
1035 * Get an object representing the default parameter state, whether
1036 * it is from the model defaults or from the saved queries.
1038 * @return {Object} Default parameters
1040 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
1041 var data
, queryHighlights
,
1043 savedHighlights
= {},
1044 defaultSavedQueryItem
= !mw
.user
.isAnon() && this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
1046 if ( defaultSavedQueryItem
) {
1047 data
= defaultSavedQueryItem
.getData();
1049 queryHighlights
= data
.highlights
|| {};
1050 savedParams
= this.filtersModel
.getParametersFromFilters(
1051 // Merge filters with sticky values
1052 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
1055 // Translate highlights to parameters
1056 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
1057 $.each( queryHighlights
, function ( filterName
, color
) {
1058 if ( filterName
!== 'highlights' ) {
1059 savedHighlights
[ filterName
+ '_color' ] = color
;
1063 return $.extend( true, {}, savedParams
, savedHighlights
);
1066 return this.filtersModel
.getDefaultParams();
1070 * Update the URL of the page to reflect current filters
1072 * This should not be called directly from outside the controller.
1073 * If an action requires changing the URL, it should either use the
1074 * highlighting actions below, or call #updateChangesList which does
1075 * the uri corrections already.
1077 * @param {Object} [params] Extra parameters to add to the API call
1079 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1080 var currentUri
= new mw
.Uri(),
1081 updatedUri
= this._getUpdatedUri();
1083 updatedUri
.extend( params
|| {} );
1086 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1087 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1089 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1094 * Get an updated mw.Uri object based on the model state
1096 * @return {mw.Uri} Updated Uri
1098 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1099 var uri
= new mw
.Uri();
1102 uri
.query
= this.uriProcessor
.minimizeQuery(
1106 // We want to retain unrecognized params
1107 // The uri params from model will override
1108 // any recognized value in the current uri
1109 // query, retain unrecognized params, and
1110 // the result will then be minimized
1112 this.uriProcessor
.getUriParametersFromModel(),
1121 * Fetch the list of changes from the server for the current filters
1123 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1124 * not to invalidate each other.
1125 * @param {Object} [params={}] Parameters to add to the query
1127 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1128 * or with a string denoting no results.
1130 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function ( counterId
, params
) {
1131 var uri
= this._getUpdatedUri(),
1132 stickyParams
= this.filtersModel
.getStickyParams(),
1136 counterId
= counterId
|| 'updateChangesList';
1137 params
= params
|| {};
1139 uri
.extend( params
);
1141 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1142 requestId
= ++this.requestCounter
[ counterId
];
1143 latestRequest = function () {
1144 return requestId
=== this.requestCounter
[ counterId
];
1147 // Sticky parameters override the URL params
1148 // this is to make sure that whether we represent
1149 // the sticky params in the URL or not (they may
1150 // be normalized out) the sticky parameters are
1151 // always being sent to the server with their
1152 // current/default values
1153 uri
.extend( stickyParams
);
1155 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1161 if ( !latestRequest() ) {
1162 return $.Deferred().reject();
1165 $parsed
= $( $.parseHTML( html
) );
1169 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1171 fieldset
: $parsed
.find( 'fieldset.cloptions' ).first()
1174 // Watchlist returns 200 when there is no results
1175 if ( pieces
.changes
.length
=== 0 ) {
1176 pieces
.changes
= 'NO_RESULTS';
1181 // RC returns 404 when there is no results
1182 function ( responseObj
) {
1185 if ( !latestRequest() ) {
1186 return $.Deferred().reject();
1189 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
1191 // Force a resolve state to this promise
1192 return $.Deferred().resolve( {
1193 changes
: 'NO_RESULTS',
1194 fieldset
: $parsed
.find( 'fieldset.cloptions' ).first()
1201 * Track usage of highlight feature
1203 * @param {string} action
1204 * @param {Array|Object|string} filters
1206 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1207 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1208 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1210 'event.ChangesListHighlights',
1214 userId
: mw
.user
.getId()
1220 * Track filter grouping usage
1222 * @param {string} action Action taken
1224 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1225 var controller
= this,
1226 rightNow
= new Date().getTime(),
1227 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1228 // Get all current filters
1229 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1230 return item
.getName();
1233 action
= action
|| 'filtermenu';
1235 // Check if these filters were the ones we just logged previously
1236 // (Don't log the same grouping twice, in case the user opens/closes)
1237 // the menu without action, or with the same result
1239 // Only log if the two arrays are different in size
1240 filters
.length
!== this.prevLoggedItems
.length
||
1241 // Or if any filters are not the same as the cached filters
1242 filters
.some( function ( filterName
) {
1243 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1245 // Or if any cached filters are not the same as given filters
1246 this.prevLoggedItems
.some( function ( filterName
) {
1247 return filters
.indexOf( filterName
) === -1;
1250 filters
.forEach( function ( filterName
) {
1252 'event.ChangesListFilterGrouping',
1255 groupIdentifier
: randomIdentifier
,
1257 userId
: mw
.user
.getId()
1262 // Cache the filter names
1263 this.prevLoggedItems
= filters
;
1268 * Mark all changes as seen on Watchlist
1270 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1271 var api
= new mw
.Api();
1272 api
.postWithToken( 'csrf', {
1274 action
: 'setnotificationtimestamp',
1275 entirewatchlist
: true
1276 } ).then( function () {
1277 this.updateChangesList( null, 'markSeen' );
1280 }( mediaWiki
, jQuery
) );