2 /* eslint no-underscore-dangle: "off" */
4 * Controller for the filters in Recent Changes
8 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
9 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
10 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
12 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
) {
13 this.filtersModel
= filtersModel
;
14 this.changesListModel
= changesListModel
;
15 this.savedQueriesModel
= savedQueriesModel
;
16 this.requestCounter
= {};
17 this.baseFilterState
= {};
18 this.uriProcessor
= null;
19 this.initializing
= false;
21 this.prevLoggedItems
= [];
25 OO
.initClass( mw
.rcfilters
.Controller
);
28 * Initialize the filter and parameter states
30 * @param {Array} filterStructure Filter definition and structure for the model
31 * @param {Object} [namespaceStructure] Namespace definition
32 * @param {Object} [tagList] Tag definition
34 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
35 var parsedSavedQueries
, limitDefault
,
40 $changesList
= $( '.mw-changeslist' ).first().contents();
43 if ( namespaceStructure
) {
45 $.each( namespaceStructure
, function ( namespaceID
, label
) {
46 // Build and clean up the individual namespace items definition
49 label
: label
|| mw
.msg( 'blanknamespace' ),
52 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
55 cssClass
: 'mw-changeslist-ns-' + namespaceID
60 title
: mw
.msg( 'namespaces' ),
63 // Group definition (single group)
64 name
: 'namespace', // parameter name is singular
65 type
: 'string_options',
66 title
: mw
.msg( 'namespaces' ),
67 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
76 title
: mw
.msg( 'rcfilters-view-tags' ),
79 // Group definition (single group)
80 name
: 'tagfilter', // Parameter name
81 type
: 'string_options',
82 title
: 'rcfilters-view-tags', // Message key
83 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
91 // Convert the default from the old preference
92 // since the limit preference actually affects more
93 // than just the RecentChanges page
94 limitDefault
= Number( mw
.user
.options
.get( 'rcfilters-rclimit', mw
.user
.options
.get( 'rclimit', '50' ) ) );
96 // Add parameter range operations
101 type
: 'single_option',
102 title
: '', // Because it's a hidden group, this title actually appears nowhere
104 allowArbitrary
: true,
105 validate
: $.isNumeric
,
106 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
107 'default': String( limitDefault
),
108 // Temporarily making this not sticky until we resolve the problem
109 // with the misleading preference. Note that if this is to be permanent
110 // we should remove all sticky behavior methods completely
113 filters
: [ 50, 100, 250, 500 ].map( function ( num
) {
114 return controller
._createFilterDataFromNumber( num
, num
);
119 type
: 'single_option',
120 title
: '', // Because it's a hidden group, this title actually appears nowhere
122 allowArbitrary
: true,
123 validate
: $.isNumeric
,
124 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
125 numToLabelFunc: function ( i
) {
126 return Number( i
) < 1 ?
127 ( Number( i
) * 24 ).toFixed( 2 ) :
130 'default': mw
.user
.options
.get( 'rcdays', '30' ),
131 // Temporarily making this not sticky while limit is not sticky, see above
134 // Hours (1, 2, 6, 12)
135 0.04166, 0.0833, 0.25, 0.5,
138 ].map( function ( num
) {
139 return controller
._createFilterDataFromNumber(
141 // Convert fractions of days to number of hours for the labels
142 num
< 1 ? Math
.round( num
* 24 ) : num
149 // Before we do anything, we need to see if we require additional items in the
150 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
151 // groups; if we ever expand it, this might need further generalization:
152 $.each( views
, function ( viewName
, viewData
) {
153 viewData
.groups
.forEach( function ( groupData
) {
154 var extraValues
= [];
155 if ( groupData
.allowArbitrary
) {
156 // If the value in the URI isn't in the group, add it
157 if ( uri
.query
[ groupData
.name
] !== undefined ) {
158 extraValues
.push( uri
.query
[ groupData
.name
] );
160 // If the default value isn't in the group, add it
161 if ( groupData
.default !== undefined ) {
162 extraValues
.push( String( groupData
.default ) );
164 controller
.addNumberValuesToGroup( groupData
, extraValues
);
169 // Initialize the model
170 this.filtersModel
.initializeFilters( filterStructure
, views
);
172 this._buildBaseFilterState();
174 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
179 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
181 parsedSavedQueries
= {};
184 // The queries are saved in a minimized state, so we need
185 // to send over the base state so the saved queries model
186 // can normalize them per each query item
187 this.savedQueriesModel
.initialize(
189 this._getBaseFilterState(),
190 // This is for backwards compatibility - delete all sticky filter states
191 Object
.keys( this.filtersModel
.getStickyFiltersState() )
194 // Check whether we need to load defaults.
195 // We do this by checking whether the current URI query
196 // contains any parameters recognized by the system.
197 // If it does, we load the given state.
198 // If it doesn't, we have no values at all, and we assume
199 // the user loads the base-page and we load defaults.
200 // Defaults should only be applied on load (if necessary)
202 this.initializing
= true;
204 this.savedQueriesModel
.getDefault() &&
205 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
207 // We have defaults from a saved query.
208 // We will load them straight-forward (as if
209 // they were clicked in the menu) so we trigger
210 // a full ajax request and change of URL
211 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
213 // There are either recognized parameters in the URL
214 // or there are none, but there is also no default
215 // saved query (so defaults are from the backend)
216 // We want to update the state but not fetch results
218 this.updateStateFromUrl( false );
220 // Update the changes list with the existing data
221 // so it gets processed
222 this.changesListModel
.update(
223 $changesList
.length
? $changesList
: 'NO_RESULTS',
224 $( 'fieldset.rcoptions' ).first(),
225 true // We're using existing DOM elements
229 this.initializing
= false;
230 this.switchView( 'default' );
232 this._scheduleLiveUpdate();
236 * Create filter data from a number, for the filters that are numerical value
238 * @param {Number} num Number
239 * @param {Number} numForDisplay Number for the label
240 * @return {Object} Filter data
242 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
245 label
: mw
.language
.convertNumber( numForDisplay
)
250 * Add an arbitrary values to groups that allow arbitrary values
252 * @param {Object} groupData Group data
253 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
255 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
256 var controller
= this;
258 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
260 // This is only true for single_option group
261 // We assume these are the only groups that will allow for
262 // arbitrary, since it doesn't make any sense for the other
264 arbitraryValues
.forEach( function ( val
) {
266 // If the group allows for arbitrary data
267 groupData
.allowArbitrary
&&
268 // and it is single_option (or string_options, but we
269 // don't have cases of those yet, nor do we plan to)
270 groupData
.type
=== 'single_option' &&
271 // and, if there is a validate method and it passes on
273 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
274 // but if that value isn't already in the definition
276 .map( function ( filterData
) {
277 return filterData
.name
;
279 .indexOf( val
) === -1
281 // Add the filter information
282 groupData
.filters
.push( controller
._createFilterDataFromNumber(
284 groupData
.numToLabelFunc
?
285 groupData
.numToLabelFunc( val
) :
289 // If there's a sort function set up, re-sort the values
290 if ( groupData
.sortFunc
) {
291 groupData
.filters
.sort( groupData
.sortFunc
);
298 * Switch the view of the filters model
300 * @param {string} view Requested view
302 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
303 this.filtersModel
.switchView( view
);
307 * Reset to default filters
309 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
310 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
312 this.updateChangesList();
316 * Empty all selected filters
318 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
319 var highlightedFilterNames
= this.filtersModel
320 .getHighlightedItems()
321 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
323 this.filtersModel
.emptyAllFilters();
324 this.filtersModel
.clearAllHighlightColors();
325 // Check all filter interactions
326 this.filtersModel
.reassessFilterInteractions();
328 this.updateChangesList();
330 if ( highlightedFilterNames
) {
331 this._trackHighlight( 'clearAll', highlightedFilterNames
);
336 * Update the selected state of a filter
338 * @param {string} filterName Filter name
339 * @param {boolean} [isSelected] Filter selected state
341 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
342 var filterItem
= this.filtersModel
.getItemByName( filterName
);
345 // If no filter was found, break
349 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
351 if ( filterItem
.isSelected() !== isSelected
) {
352 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
354 this.updateChangesList();
356 // Check filter interactions
357 this.filtersModel
.reassessFilterInteractions( filterItem
);
362 * Clear both highlight and selection of a filter
364 * @param {string} filterName Name of the filter item
366 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
367 var filterItem
= this.filtersModel
.getItemByName( filterName
),
368 isHighlighted
= filterItem
.isHighlighted();
370 if ( filterItem
.isSelected() || isHighlighted
) {
371 this.filtersModel
.clearHighlightColor( filterName
);
372 this.filtersModel
.toggleFilterSelected( filterName
, false );
373 this.updateChangesList();
374 this.filtersModel
.reassessFilterInteractions( filterItem
);
376 // Log filter grouping
377 this.trackFilterGroupings( 'removefilter' );
380 if ( isHighlighted
) {
381 this._trackHighlight( 'clear', filterName
);
386 * Toggle the highlight feature on and off
388 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
389 this.filtersModel
.toggleHighlight();
392 if ( this.filtersModel
.isHighlightEnabled() ) {
393 mw
.hook( 'RcFilters.highlight.enable' ).fire();
398 * Toggle the namespaces inverted feature on and off
400 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
401 this.filtersModel
.toggleInvertedNamespaces();
404 this.filtersModel
.getFiltersByView( 'namespaces' )
405 .filter( function ( filterItem
) {
406 return filterItem
.isSelected();
410 // Only re-fetch results if there are namespace items that are actually selected
411 this.updateChangesList();
416 * Set the highlight color for a filter item
418 * @param {string} filterName Name of the filter item
419 * @param {string} color Selected color
421 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
422 this.filtersModel
.setHighlightColor( filterName
, color
);
424 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
428 * Clear highlight for a filter item
430 * @param {string} filterName Name of the filter item
432 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
433 this.filtersModel
.clearHighlightColor( filterName
);
435 this._trackHighlight( 'clear', filterName
);
439 * Enable or disable live updates.
440 * @param {boolean} enable True to enable, false to disable
442 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
443 this.changesListModel
.toggleLiveUpdate( enable
);
444 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
445 this.showNewChanges();
450 * Set a timeout for the next live update.
453 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
454 setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
458 * Perform a live update.
461 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
462 if ( !this._shouldCheckForNewChanges() ) {
463 // skip this turn and check back later
464 this._scheduleLiveUpdate();
468 this._checkForNewChanges()
469 .then( function ( data
) {
470 if ( !this._shouldCheckForNewChanges() ) {
471 // by the time the response is received,
472 // it may not be appropriate anymore
476 if ( data
.changes
!== 'NO_RESULTS' ) {
477 if ( this.changesListModel
.getLiveUpdate() ) {
478 return this.updateChangesList( false, null, true, false );
480 this.changesListModel
.setNewChangesExist( true );
484 .always( this._scheduleLiveUpdate
.bind( this ) );
488 * @return {boolean} It's appropriate to check for new changes now
491 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
492 var liveUpdateFeatureFlag
= mw
.config
.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
493 new mw
.Uri().query
.liveupdate
;
495 return !document
.hidden
&&
496 !this.changesListModel
.getNewChangesExist() &&
497 !this.updatingChangesList
&&
498 liveUpdateFeatureFlag
;
502 * Check if new changes, newer than those currently shown, are available
504 * @return {jQuery.Promise} Promise object that resolves after trying
505 * to fetch 1 change newer than the last known 'from' parameter value
509 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
510 return this._fetchChangesList(
514 from: this.changesListModel
.getNextFrom()
520 * Show the new changes
522 * @return {jQuery.Promise} Promise object that resolves after
523 * fetching and showing the new changes
525 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
526 return this.updateChangesList( false, null, true, true );
530 * Save the current model state as a saved query
532 * @param {string} [label] Label of the saved query
533 * @param {boolean} [setAsDefault=false] This query should be set as the default
535 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
537 highlightedItems
= {},
538 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
539 selectedState
= this.filtersModel
.getSelectedState();
541 // Prepare highlights
542 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
543 highlightedItems
[ item
.getName() ] = highlightEnabled
?
544 item
.getHighlightColor() : null;
546 // These are filter states; highlight is stored as boolean
547 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
549 // Delete all sticky filters
550 this._deleteStickyValuesFromFilterState( selectedState
);
553 queryID
= this.savedQueriesModel
.addNewQuery(
554 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
556 filters
: selectedState
,
557 highlights
: highlightedItems
,
558 invert
: this.filtersModel
.areNamespacesInverted()
562 if ( setAsDefault
) {
563 this.savedQueriesModel
.setDefault( queryID
);
567 this._saveSavedQueries();
571 * Remove a saved query
573 * @param {string} queryID Query id
575 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
576 this.savedQueriesModel
.removeQuery( queryID
);
578 this._saveSavedQueries();
582 * Rename a saved query
584 * @param {string} queryID Query id
585 * @param {string} newLabel New label for the query
587 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
588 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
591 queryItem
.updateLabel( newLabel
);
593 this._saveSavedQueries();
597 * Set a saved query as default
599 * @param {string} queryID Query Id. If null is given, default
602 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
603 this.savedQueriesModel
.setDefault( queryID
);
604 this._saveSavedQueries();
610 * @param {string} queryID Query id
612 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
613 var data
, highlights
,
614 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
615 currentMatchingQuery
= this.findQueryMatchingCurrentState();
620 // If there's already a query, don't reload it
621 // if it's the same as the one that already exists
622 !currentMatchingQuery
||
623 currentMatchingQuery
.getID() !== queryItem
.getID()
626 data
= queryItem
.getData();
627 highlights
= data
.highlights
;
629 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
630 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
632 // Update model state from filters
633 this.filtersModel
.toggleFiltersSelected(
634 // Merge filters with sticky values
635 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
638 // Update namespace inverted property
639 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
641 // Update highlight state
642 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
643 this.filtersModel
.getItems().forEach( function ( filterItem
) {
644 var color
= highlights
[ filterItem
.getName() ];
646 filterItem
.setHighlightColor( color
);
648 filterItem
.clearHighlightColor();
652 // Check all filter interactions
653 this.filtersModel
.reassessFilterInteractions();
655 this.updateChangesList();
657 // Log filter grouping
658 this.trackFilterGroupings( 'savedfilters' );
663 * Check whether the current filter and highlight state exists
664 * in the saved queries model.
666 * @return {boolean} Query exists
668 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
669 var highlightedItems
= {},
670 selectedState
= this.filtersModel
.getSelectedState();
672 // Prepare highlights of the current query
673 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
674 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
676 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
678 // Remove sticky filters
679 this._deleteStickyValuesFromFilterState( selectedState
);
681 return this.savedQueriesModel
.findMatchingQuery(
683 filters
: selectedState
,
684 highlights
: highlightedItems
,
685 invert
: this.filtersModel
.areNamespacesInverted()
691 * Delete sticky filters from given object
693 * @param {Object} filterState Filter state
695 mw
.rcfilters
.Controller
.prototype._deleteStickyValuesFromFilterState = function ( filterState
) {
696 // Remove sticky filters
697 $.each( this.filtersModel
.getStickyFiltersState(), function ( filterName
) {
698 delete filterState
[ filterName
];
703 * Get an object representing the base state of parameters
706 * This is meant to make sure that the saved queries that are
707 * in memory are always the same structure as what we would get
708 * by calling the current model's "getSelectedState" and by checking
711 * In cases where a user saved a query when the system had a certain
712 * set of filters, and then a filter was added to the system, we want
713 * to make sure that the stored queries can still be comparable to
714 * the current state, which means that we need the base state for
717 * - Saved queries are stored in "minimal" view (only changed filters
718 * are stored); When we initialize the system, we merge each minimal
719 * query with the base state (using 'getNormalizedFilters') so all
720 * saved queries have the exact same structure as what we would get
721 * by checking the getSelectedState of the filter.
722 * - When we save the queries, we minimize the object to only represent
723 * whatever has actually changed, rather than store the entire
724 * object. To check what actually is different so we can store it,
725 * we need to obtain a base state to compare against, this is
726 * what #_getMinimalFilterList does
728 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
729 var defaultParams
= this.filtersModel
.getDefaultParams(),
730 highlightedItems
= {};
732 // Prepare highlights
733 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
734 highlightedItems
[ item
.getName() ] = null;
736 highlightedItems
.highlight
= false;
738 this.baseFilterState
= {
739 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
740 highlights
: highlightedItems
,
746 * Get an object representing the base filter state of both
747 * filters and highlights. The structure is similar to what we use
748 * to store each query in the saved queries object:
754 * filterName: (string|null)
758 * @return {Object} Object representing the base state of
759 * parameters and highlights
761 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
762 return this.baseFilterState
;
766 * Get an object that holds only the parameters and highlights that have
767 * values different than the base default value.
769 * This is the reverse of the normalization we do initially on loading and
770 * initializing the saved queries model.
772 * @param {Object} valuesObject Object representing the state of both
773 * filters and highlights in its normalized version, to be minimized.
774 * @return {Object} Minimal filters and highlights list
776 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
777 var result
= { filters
: {}, highlights
: {} },
778 baseState
= this._getBaseFilterState();
781 $.each( valuesObject
.filters
, function ( name
, value
) {
782 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
783 result
.filters
[ name
] = value
;
787 $.each( valuesObject
.highlights
, function ( name
, value
) {
788 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
789 result
.highlights
[ name
] = value
;
797 * Save the current state of the saved queries model with all
798 * query item representation in the user settings.
800 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
802 state
= this.savedQueriesModel
.getState(),
805 // Minimize before save
806 $.each( state
.queries
, function ( queryID
, info
) {
807 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
811 stringified
= JSON
.stringify( state
);
813 if ( stringified
.length
> 65535 ) {
814 // Sanity check, since the preference can only hold that.
818 // Save the preference
819 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
820 // Update the preference for this session
821 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
825 * Update sticky preferences with current model state
827 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
828 // Update default sticky values with selected, whether they came from
829 // the initial defaults or from the URL value that is being normalized
830 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
831 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
835 * Update the limit default value
837 * param {number} newValue New value
839 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
840 // HACK: Temporarily remove this from being sticky
844 if ( !$.isNumeric( newValue ) ) {
848 newValue = Number( newValue );
850 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
851 // Save the preference
852 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
853 // Update the preference for this session
854 mw.user.options.set( 'rcfilters-rclimit', newValue );
861 * Update the days default value
863 * param {number} newValue New value
865 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
866 // HACK: Temporarily remove this from being sticky
870 if ( !$.isNumeric( newValue ) ) {
874 newValue = Number( newValue );
876 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
877 // Save the preference
878 new mw.Api().saveOption( 'rcdays', newValue );
879 // Update the preference for this session
880 mw.user.options.set( 'rcdays', newValue );
887 * Synchronize the URL with the current state of the filters
888 * without adding an history entry.
890 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
891 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
895 * Update filter state (selection and highlighting) based
896 * on current URL values.
898 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
899 * list based on the updated model.
901 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
902 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
904 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
906 // Update the sticky preferences, in case we received a value
908 this.updateStickyPreferences();
910 // Only update and fetch new results if it is requested
911 if ( fetchChangesList
) {
912 this.updateChangesList();
917 * Update the list of changes and notify the model
919 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
920 * @param {Object} [params] Extra parameters to add to the API call
921 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
922 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
923 * @return {jQuery.Promise} Promise that is resolved when the update is complete
925 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( updateUrl
, params
, isLiveUpdate
, invalidateCurrentChanges
) {
926 updateUrl
= updateUrl
=== undefined ? true : updateUrl
;
927 invalidateCurrentChanges
= invalidateCurrentChanges
=== undefined ? true : invalidateCurrentChanges
;
929 this._updateURL( params
);
931 if ( invalidateCurrentChanges
) {
932 this.changesListModel
.invalidate();
934 this.changesListModel
.setNewChangesExist( false );
935 this.updatingChangesList
= true;
936 return this._fetchChangesList()
939 function ( pieces
) {
940 var $changesListContent
= pieces
.changes
,
941 $fieldset
= pieces
.fieldset
;
942 this.changesListModel
.update( $changesListContent
, $fieldset
, false, isLiveUpdate
);
944 // Do nothing for failure
946 .always( function () {
947 this.updatingChangesList
= false;
952 * Get an object representing the default parameter state, whether
953 * it is from the model defaults or from the saved queries.
955 * @return {Object} Default parameters
957 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
958 var data
, queryHighlights
,
960 savedHighlights
= {},
961 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
963 if ( defaultSavedQueryItem
) {
964 data
= defaultSavedQueryItem
.getData();
966 queryHighlights
= data
.highlights
|| {};
967 savedParams
= this.filtersModel
.getParametersFromFilters(
968 // Merge filters with sticky values
969 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
972 // Translate highlights to parameters
973 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
974 $.each( queryHighlights
, function ( filterName
, color
) {
975 if ( filterName
!== 'highlights' ) {
976 savedHighlights
[ filterName
+ '_color' ] = color
;
980 return $.extend( true, {}, savedParams
, savedHighlights
);
983 return this.filtersModel
.getDefaultParams();
987 * Update the URL of the page to reflect current filters
989 * This should not be called directly from outside the controller.
990 * If an action requires changing the URL, it should either use the
991 * highlighting actions below, or call #updateChangesList which does
992 * the uri corrections already.
994 * @param {Object} [params] Extra parameters to add to the API call
996 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
997 var currentUri
= new mw
.Uri(),
998 updatedUri
= this._getUpdatedUri();
1000 updatedUri
.extend( params
|| {} );
1003 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1004 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1006 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1011 * Get an updated mw.Uri object based on the model state
1013 * @return {mw.Uri} Updated Uri
1015 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1016 var uri
= new mw
.Uri();
1019 uri
.query
= this.uriProcessor
.minimizeQuery(
1023 // We want to retain unrecognized params
1024 // The uri params from model will override
1025 // any recognized value in the current uri
1026 // query, retain unrecognized params, and
1027 // the result will then be minimized
1029 this.uriProcessor
.getUriParametersFromModel(),
1038 * Fetch the list of changes from the server for the current filters
1040 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1041 * not to invalidate each other.
1042 * @param {Object} [params={}] Parameters to add to the query
1044 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1045 * or with a string denoting no results.
1047 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function ( counterId
, params
) {
1048 var uri
= this._getUpdatedUri(),
1049 stickyParams
= this.filtersModel
.getStickyParams(),
1053 counterId
= counterId
|| 'updateChangesList';
1054 params
= params
|| {};
1056 uri
.extend( params
);
1058 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1059 requestId
= ++this.requestCounter
[ counterId
];
1060 latestRequest = function () {
1061 return requestId
=== this.requestCounter
[ counterId
];
1064 // Sticky parameters override the URL params
1065 // this is to make sure that whether we represent
1066 // the sticky params in the URL or not (they may
1067 // be normalized out) the sticky parameters are
1068 // always being sent to the server with their
1069 // current/default values
1070 uri
.extend( stickyParams
);
1072 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1077 if ( !latestRequest() ) {
1078 return $.Deferred().reject();
1081 $parsed
= $( $.parseHTML( html
) );
1085 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1087 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1091 function ( responseObj
) {
1094 if ( !latestRequest() ) {
1095 return $.Deferred().reject();
1098 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
1100 // Force a resolve state to this promise
1101 return $.Deferred().resolve( {
1102 changes
: 'NO_RESULTS',
1103 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1110 * Track usage of highlight feature
1112 * @param {string} action
1113 * @param {Array|Object|string} filters
1115 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1116 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1117 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1119 'event.ChangesListHighlights',
1123 userId
: mw
.user
.getId()
1129 * Track filter grouping usage
1131 * @param {string} action Action taken
1133 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1134 var controller
= this,
1135 rightNow
= new Date().getTime(),
1136 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1137 // Get all current filters
1138 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1139 return item
.getName();
1142 action
= action
|| 'filtermenu';
1144 // Check if these filters were the ones we just logged previously
1145 // (Don't log the same grouping twice, in case the user opens/closes)
1146 // the menu without action, or with the same result
1148 // Only log if the two arrays are different in size
1149 filters
.length
!== this.prevLoggedItems
.length
||
1150 // Or if any filters are not the same as the cached filters
1151 filters
.some( function ( filterName
) {
1152 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1154 // Or if any cached filters are not the same as given filters
1155 this.prevLoggedItems
.some( function ( filterName
) {
1156 return filters
.indexOf( filterName
) === -1;
1159 filters
.forEach( function ( filterName
) {
1161 'event.ChangesListFilterGrouping',
1164 groupIdentifier
: randomIdentifier
,
1166 userId
: mw
.user
.getId()
1171 // Cache the filter names
1172 this.prevLoggedItems
= filters
;
1175 }( mediaWiki
, jQuery
) );