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
,
36 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
41 $changesList
= $( '.mw-changeslist' ).first().contents();
44 if ( namespaceStructure
) {
46 $.each( namespaceStructure
, function ( namespaceID
, label
) {
47 // Build and clean up the individual namespace items definition
50 label
: label
|| mw
.msg( 'blanknamespace' ),
53 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
56 cssClass
: 'mw-changeslist-ns-' + namespaceID
61 title
: mw
.msg( 'namespaces' ),
64 // Group definition (single group)
65 name
: 'namespace', // parameter name is singular
66 type
: 'string_options',
67 title
: mw
.msg( 'namespaces' ),
68 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
77 title
: mw
.msg( 'rcfilters-view-tags' ),
80 // Group definition (single group)
81 name
: 'tagfilter', // Parameter name
82 type
: 'string_options',
83 title
: 'rcfilters-view-tags', // Message key
84 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
92 // Convert the default from the old preference
93 // since the limit preference actually affects more
94 // than just the RecentChanges page
95 limitDefault
= Number( mw
.user
.options
.get( 'rcfilters-rclimit', mw
.user
.options
.get( 'rclimit', '50' ) ) );
97 // Add parameter range operations
102 type
: 'single_option',
103 title
: '', // Because it's a hidden group, this title actually appears nowhere
105 allowArbitrary
: true,
106 validate
: $.isNumeric
,
111 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
112 'default': String( limitDefault
),
113 // Temporarily making this not sticky until we resolve the problem
114 // with the misleading preference. Note that if this is to be permanent
115 // we should remove all sticky behavior methods completely
118 filters
: displayConfig
.arrayLimit
.map( function ( num
) {
119 return controller
._createFilterDataFromNumber( num
, num
);
124 type
: 'single_option',
125 title
: '', // Because it's a hidden group, this title actually appears nowhere
127 allowArbitrary
: true,
128 validate
: $.isNumeric
,
131 max
: displayConfig
.maxLimit
133 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
134 numToLabelFunc: function ( i
) {
135 return Number( i
) < 1 ?
136 ( Number( i
) * 24 ).toFixed( 2 ) :
139 'default': mw
.user
.options
.get( 'rcdays', '30' ),
140 // Temporarily making this not sticky while limit is not sticky, see above
143 // Hours (1, 2, 6, 12)
144 0.04166, 0.0833, 0.25, 0.5
146 ].concat( displayConfig
.arrayDays
)
147 .map( function ( num
) {
148 return controller
._createFilterDataFromNumber(
150 // Convert fractions of days to number of hours for the labels
151 num
< 1 ? Math
.round( num
* 24 ) : num
163 title
: '', // Because it's a hidden group, this title actually appears nowhere
169 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
176 // Before we do anything, we need to see if we require additional items in the
177 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
178 // groups; if we ever expand it, this might need further generalization:
179 $.each( views
, function ( viewName
, viewData
) {
180 viewData
.groups
.forEach( function ( groupData
) {
181 var extraValues
= [];
182 if ( groupData
.allowArbitrary
) {
183 // If the value in the URI isn't in the group, add it
184 if ( uri
.query
[ groupData
.name
] !== undefined ) {
185 extraValues
.push( uri
.query
[ groupData
.name
] );
187 // If the default value isn't in the group, add it
188 if ( groupData
.default !== undefined ) {
189 extraValues
.push( String( groupData
.default ) );
191 controller
.addNumberValuesToGroup( groupData
, extraValues
);
196 // Initialize the model
197 this.filtersModel
.initializeFilters( filterStructure
, views
);
199 this._buildBaseFilterState();
201 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
206 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
208 parsedSavedQueries
= {};
211 // The queries are saved in a minimized state, so we need
212 // to send over the base state so the saved queries model
213 // can normalize them per each query item
214 this.savedQueriesModel
.initialize(
216 this._getBaseFilterState(),
217 // This is for backwards compatibility - delete all sticky filter states
218 Object
.keys( this.filtersModel
.getStickyFiltersState() )
221 // Check whether we need to load defaults.
222 // We do this by checking whether the current URI query
223 // contains any parameters recognized by the system.
224 // If it does, we load the given state.
225 // If it doesn't, we have no values at all, and we assume
226 // the user loads the base-page and we load defaults.
227 // Defaults should only be applied on load (if necessary)
229 this.initializing
= true;
231 this.savedQueriesModel
.getDefault() &&
232 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
234 // We have defaults from a saved query.
235 // We will load them straight-forward (as if
236 // they were clicked in the menu) so we trigger
237 // a full ajax request and change of URL
238 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
240 // There are either recognized parameters in the URL
241 // or there are none, but there is also no default
242 // saved query (so defaults are from the backend)
243 // We want to update the state but not fetch results
245 this.updateStateFromUrl( false );
247 // Update the changes list with the existing data
248 // so it gets processed
249 this.changesListModel
.update(
250 $changesList
.length
? $changesList
: 'NO_RESULTS',
251 $( 'fieldset.rcoptions' ).first(),
252 true // We're using existing DOM elements
256 this.initializing
= false;
257 this.switchView( 'default' );
259 this._scheduleLiveUpdate();
263 * Create filter data from a number, for the filters that are numerical value
265 * @param {Number} num Number
266 * @param {Number} numForDisplay Number for the label
267 * @return {Object} Filter data
269 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
272 label
: mw
.language
.convertNumber( numForDisplay
)
277 * Add an arbitrary values to groups that allow arbitrary values
279 * @param {Object} groupData Group data
280 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
282 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
283 var controller
= this;
285 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
287 // Normalize the arbitrary values
288 if ( groupData
.range
) {
289 arbitraryValues
= arbitraryValues
.map( function ( val
) {
291 return groupData
.range
.min
; // Min
292 } else if ( val
>= groupData
.range
.max
) {
293 return groupData
.range
.max
; // Max
299 // This is only true for single_option group
300 // We assume these are the only groups that will allow for
301 // arbitrary, since it doesn't make any sense for the other
303 arbitraryValues
.forEach( function ( val
) {
305 // If the group allows for arbitrary data
306 groupData
.allowArbitrary
&&
307 // and it is single_option (or string_options, but we
308 // don't have cases of those yet, nor do we plan to)
309 groupData
.type
=== 'single_option' &&
310 // and, if there is a validate method and it passes on
312 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
313 // but if that value isn't already in the definition
315 .map( function ( filterData
) {
316 return String( filterData
.name
);
318 .indexOf( String( val
) ) === -1
320 // Add the filter information
321 groupData
.filters
.push( controller
._createFilterDataFromNumber(
323 groupData
.numToLabelFunc
?
324 groupData
.numToLabelFunc( val
) :
328 // If there's a sort function set up, re-sort the values
329 if ( groupData
.sortFunc
) {
330 groupData
.filters
.sort( groupData
.sortFunc
);
337 * Switch the view of the filters model
339 * @param {string} view Requested view
341 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
342 this.filtersModel
.switchView( view
);
346 * Reset to default filters
348 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
349 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
351 this.updateChangesList();
355 * Empty all selected filters
357 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
358 var highlightedFilterNames
= this.filtersModel
359 .getHighlightedItems()
360 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
362 this.filtersModel
.emptyAllFilters();
363 this.filtersModel
.clearAllHighlightColors();
364 // Check all filter interactions
365 this.filtersModel
.reassessFilterInteractions();
367 this.updateChangesList();
369 if ( highlightedFilterNames
) {
370 this._trackHighlight( 'clearAll', highlightedFilterNames
);
375 * Update the selected state of a filter
377 * @param {string} filterName Filter name
378 * @param {boolean} [isSelected] Filter selected state
380 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
381 var filterItem
= this.filtersModel
.getItemByName( filterName
);
384 // If no filter was found, break
388 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
390 if ( filterItem
.isSelected() !== isSelected
) {
391 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
393 this.updateChangesList();
395 // Check filter interactions
396 this.filtersModel
.reassessFilterInteractions( filterItem
);
401 * Clear both highlight and selection of a filter
403 * @param {string} filterName Name of the filter item
405 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
406 var filterItem
= this.filtersModel
.getItemByName( filterName
),
407 isHighlighted
= filterItem
.isHighlighted();
409 if ( filterItem
.isSelected() || isHighlighted
) {
410 this.filtersModel
.clearHighlightColor( filterName
);
411 this.filtersModel
.toggleFilterSelected( filterName
, false );
412 this.updateChangesList();
413 this.filtersModel
.reassessFilterInteractions( filterItem
);
415 // Log filter grouping
416 this.trackFilterGroupings( 'removefilter' );
419 if ( isHighlighted
) {
420 this._trackHighlight( 'clear', filterName
);
425 * Toggle the highlight feature on and off
427 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
428 this.filtersModel
.toggleHighlight();
431 if ( this.filtersModel
.isHighlightEnabled() ) {
432 mw
.hook( 'RcFilters.highlight.enable' ).fire();
437 * Toggle the namespaces inverted feature on and off
439 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
440 this.filtersModel
.toggleInvertedNamespaces();
443 this.filtersModel
.getFiltersByView( 'namespaces' )
444 .filter( function ( filterItem
) {
445 return filterItem
.isSelected();
449 // Only re-fetch results if there are namespace items that are actually selected
450 this.updateChangesList();
455 * Set the highlight color for a filter item
457 * @param {string} filterName Name of the filter item
458 * @param {string} color Selected color
460 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
461 this.filtersModel
.setHighlightColor( filterName
, color
);
463 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
467 * Clear highlight for a filter item
469 * @param {string} filterName Name of the filter item
471 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
472 this.filtersModel
.clearHighlightColor( filterName
);
474 this._trackHighlight( 'clear', filterName
);
478 * Enable or disable live updates.
479 * @param {boolean} enable True to enable, false to disable
481 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
482 this.changesListModel
.toggleLiveUpdate( enable
);
483 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
484 this.showNewChanges();
489 * Set a timeout for the next live update.
492 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
493 setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
497 * Perform a live update.
500 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
501 if ( !this._shouldCheckForNewChanges() ) {
502 // skip this turn and check back later
503 this._scheduleLiveUpdate();
507 this._checkForNewChanges()
508 .then( function ( data
) {
509 if ( !this._shouldCheckForNewChanges() ) {
510 // by the time the response is received,
511 // it may not be appropriate anymore
515 if ( data
.changes
!== 'NO_RESULTS' ) {
516 if ( this.changesListModel
.getLiveUpdate() ) {
517 return this.updateChangesList( false, null, true, false );
519 this.changesListModel
.setNewChangesExist( true );
523 .always( this._scheduleLiveUpdate
.bind( this ) );
527 * @return {boolean} It's appropriate to check for new changes now
530 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
531 var liveUpdateFeatureFlag
= mw
.config
.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
532 new mw
.Uri().query
.liveupdate
;
534 return !document
.hidden
&&
535 !this.changesListModel
.getNewChangesExist() &&
536 !this.updatingChangesList
&&
537 liveUpdateFeatureFlag
;
541 * Check if new changes, newer than those currently shown, are available
543 * @return {jQuery.Promise} Promise object that resolves after trying
544 * to fetch 1 change newer than the last known 'from' parameter value
548 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
549 return this._fetchChangesList(
553 from: this.changesListModel
.getNextFrom()
559 * Show the new changes
561 * @return {jQuery.Promise} Promise object that resolves after
562 * fetching and showing the new changes
564 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
565 return this.updateChangesList( false, null, true, true );
569 * Save the current model state as a saved query
571 * @param {string} [label] Label of the saved query
572 * @param {boolean} [setAsDefault=false] This query should be set as the default
574 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
576 highlightedItems
= {},
577 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
578 selectedState
= this.filtersModel
.getSelectedState();
580 // Prepare highlights
581 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
582 highlightedItems
[ item
.getName() ] = highlightEnabled
?
583 item
.getHighlightColor() : null;
585 // These are filter states; highlight is stored as boolean
586 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
588 // Delete all sticky filters
589 this._deleteStickyValuesFromFilterState( selectedState
);
592 queryID
= this.savedQueriesModel
.addNewQuery(
593 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
595 filters
: selectedState
,
596 highlights
: highlightedItems
,
597 invert
: this.filtersModel
.areNamespacesInverted()
601 if ( setAsDefault
) {
602 this.savedQueriesModel
.setDefault( queryID
);
606 this._saveSavedQueries();
610 * Remove a saved query
612 * @param {string} queryID Query id
614 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
615 this.savedQueriesModel
.removeQuery( queryID
);
617 this._saveSavedQueries();
621 * Rename a saved query
623 * @param {string} queryID Query id
624 * @param {string} newLabel New label for the query
626 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
627 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
630 queryItem
.updateLabel( newLabel
);
632 this._saveSavedQueries();
636 * Set a saved query as default
638 * @param {string} queryID Query Id. If null is given, default
641 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
642 this.savedQueriesModel
.setDefault( queryID
);
643 this._saveSavedQueries();
649 * @param {string} queryID Query id
651 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
652 var data
, highlights
,
653 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
654 currentMatchingQuery
= this.findQueryMatchingCurrentState();
659 // If there's already a query, don't reload it
660 // if it's the same as the one that already exists
661 !currentMatchingQuery
||
662 currentMatchingQuery
.getID() !== queryItem
.getID()
665 data
= queryItem
.getData();
666 highlights
= data
.highlights
;
668 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
669 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
671 // Update model state from filters
672 this.filtersModel
.toggleFiltersSelected(
673 // Merge filters with sticky values
674 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
677 // Update namespace inverted property
678 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
680 // Update highlight state
681 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
682 this.filtersModel
.getItems().forEach( function ( filterItem
) {
683 var color
= highlights
[ filterItem
.getName() ];
685 filterItem
.setHighlightColor( color
);
687 filterItem
.clearHighlightColor();
691 // Check all filter interactions
692 this.filtersModel
.reassessFilterInteractions();
694 this.updateChangesList();
696 // Log filter grouping
697 this.trackFilterGroupings( 'savedfilters' );
702 * Check whether the current filter and highlight state exists
703 * in the saved queries model.
705 * @return {boolean} Query exists
707 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
708 var highlightedItems
= {},
709 selectedState
= this.filtersModel
.getSelectedState();
711 // Prepare highlights of the current query
712 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
713 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
715 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
717 // Remove sticky filters
718 this._deleteStickyValuesFromFilterState( selectedState
);
720 return this.savedQueriesModel
.findMatchingQuery(
722 filters
: selectedState
,
723 highlights
: highlightedItems
,
724 invert
: this.filtersModel
.areNamespacesInverted()
730 * Delete sticky filters from given object
732 * @param {Object} filterState Filter state
734 mw
.rcfilters
.Controller
.prototype._deleteStickyValuesFromFilterState = function ( filterState
) {
735 // Remove sticky filters
736 $.each( this.filtersModel
.getStickyFiltersState(), function ( filterName
) {
737 delete filterState
[ filterName
];
742 * Get an object representing the base state of parameters
745 * This is meant to make sure that the saved queries that are
746 * in memory are always the same structure as what we would get
747 * by calling the current model's "getSelectedState" and by checking
750 * In cases where a user saved a query when the system had a certain
751 * set of filters, and then a filter was added to the system, we want
752 * to make sure that the stored queries can still be comparable to
753 * the current state, which means that we need the base state for
756 * - Saved queries are stored in "minimal" view (only changed filters
757 * are stored); When we initialize the system, we merge each minimal
758 * query with the base state (using 'getNormalizedFilters') so all
759 * saved queries have the exact same structure as what we would get
760 * by checking the getSelectedState of the filter.
761 * - When we save the queries, we minimize the object to only represent
762 * whatever has actually changed, rather than store the entire
763 * object. To check what actually is different so we can store it,
764 * we need to obtain a base state to compare against, this is
765 * what #_getMinimalFilterList does
767 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
768 var defaultParams
= this.filtersModel
.getDefaultParams(),
769 highlightedItems
= {};
771 // Prepare highlights
772 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
773 highlightedItems
[ item
.getName() ] = null;
775 highlightedItems
.highlight
= false;
777 this.baseFilterState
= {
778 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
779 highlights
: highlightedItems
,
785 * Get an object representing the base filter state of both
786 * filters and highlights. The structure is similar to what we use
787 * to store each query in the saved queries object:
793 * filterName: (string|null)
797 * @return {Object} Object representing the base state of
798 * parameters and highlights
800 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
801 return this.baseFilterState
;
805 * Get an object that holds only the parameters and highlights that have
806 * values different than the base default value.
808 * This is the reverse of the normalization we do initially on loading and
809 * initializing the saved queries model.
811 * @param {Object} valuesObject Object representing the state of both
812 * filters and highlights in its normalized version, to be minimized.
813 * @return {Object} Minimal filters and highlights list
815 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
816 var result
= { filters
: {}, highlights
: {} },
817 baseState
= this._getBaseFilterState();
820 $.each( valuesObject
.filters
, function ( name
, value
) {
821 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
822 result
.filters
[ name
] = value
;
826 $.each( valuesObject
.highlights
, function ( name
, value
) {
827 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
828 result
.highlights
[ name
] = value
;
836 * Save the current state of the saved queries model with all
837 * query item representation in the user settings.
839 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
841 state
= this.savedQueriesModel
.getState(),
844 // Minimize before save
845 $.each( state
.queries
, function ( queryID
, info
) {
846 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
850 stringified
= JSON
.stringify( state
);
852 if ( stringified
.length
> 65535 ) {
853 // Sanity check, since the preference can only hold that.
857 // Save the preference
858 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
859 // Update the preference for this session
860 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
864 * Update sticky preferences with current model state
866 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
867 // Update default sticky values with selected, whether they came from
868 // the initial defaults or from the URL value that is being normalized
869 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
870 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
872 // TODO: Make these automatic by having the model go over sticky
873 // items and update their default values automatically
877 * Update the limit default value
879 * param {number} newValue New value
881 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
882 // HACK: Temporarily remove this from being sticky
886 if ( !$.isNumeric( newValue ) ) {
890 newValue = Number( newValue );
892 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
893 // Save the preference
894 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
895 // Update the preference for this session
896 mw.user.options.set( 'rcfilters-rclimit', newValue );
903 * Update the days default value
905 * param {number} newValue New value
907 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
908 // HACK: Temporarily remove this from being sticky
912 if ( !$.isNumeric( newValue ) ) {
916 newValue = Number( newValue );
918 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
919 // Save the preference
920 new mw.Api().saveOption( 'rcdays', newValue );
921 // Update the preference for this session
922 mw.user.options.set( 'rcdays', newValue );
929 * Update the group by page default value
931 * @param {number} newValue New value
933 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
934 if ( !$.isNumeric( newValue
) ) {
938 newValue
= Number( newValue
);
940 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
941 // Save the preference
942 new mw
.Api().saveOption( 'usenewrc', newValue
);
943 // Update the preference for this session
944 mw
.user
.options
.set( 'usenewrc', newValue
);
949 * Synchronize the URL with the current state of the filters
950 * without adding an history entry.
952 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
953 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
957 * Update filter state (selection and highlighting) based
958 * on current URL values.
960 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
961 * list based on the updated model.
963 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
964 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
966 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
968 // Update the sticky preferences, in case we received a value
970 this.updateStickyPreferences();
972 // Only update and fetch new results if it is requested
973 if ( fetchChangesList
) {
974 this.updateChangesList();
979 * Update the list of changes and notify the model
981 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
982 * @param {Object} [params] Extra parameters to add to the API call
983 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
984 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
985 * @return {jQuery.Promise} Promise that is resolved when the update is complete
987 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( updateUrl
, params
, isLiveUpdate
, invalidateCurrentChanges
) {
988 updateUrl
= updateUrl
=== undefined ? true : updateUrl
;
989 invalidateCurrentChanges
= invalidateCurrentChanges
=== undefined ? true : invalidateCurrentChanges
;
991 this._updateURL( params
);
993 if ( invalidateCurrentChanges
) {
994 this.changesListModel
.invalidate();
996 this.changesListModel
.setNewChangesExist( false );
997 this.updatingChangesList
= true;
998 return this._fetchChangesList()
1001 function ( pieces
) {
1002 var $changesListContent
= pieces
.changes
,
1003 $fieldset
= pieces
.fieldset
;
1004 this.changesListModel
.update( $changesListContent
, $fieldset
, false, isLiveUpdate
);
1006 // Do nothing for failure
1008 .always( function () {
1009 this.updatingChangesList
= false;
1014 * Get an object representing the default parameter state, whether
1015 * it is from the model defaults or from the saved queries.
1017 * @return {Object} Default parameters
1019 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
1020 var data
, queryHighlights
,
1022 savedHighlights
= {},
1023 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
1025 if ( defaultSavedQueryItem
) {
1026 data
= defaultSavedQueryItem
.getData();
1028 queryHighlights
= data
.highlights
|| {};
1029 savedParams
= this.filtersModel
.getParametersFromFilters(
1030 // Merge filters with sticky values
1031 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
1034 // Translate highlights to parameters
1035 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
1036 $.each( queryHighlights
, function ( filterName
, color
) {
1037 if ( filterName
!== 'highlights' ) {
1038 savedHighlights
[ filterName
+ '_color' ] = color
;
1042 return $.extend( true, {}, savedParams
, savedHighlights
);
1045 return this.filtersModel
.getDefaultParams();
1049 * Update the URL of the page to reflect current filters
1051 * This should not be called directly from outside the controller.
1052 * If an action requires changing the URL, it should either use the
1053 * highlighting actions below, or call #updateChangesList which does
1054 * the uri corrections already.
1056 * @param {Object} [params] Extra parameters to add to the API call
1058 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1059 var currentUri
= new mw
.Uri(),
1060 updatedUri
= this._getUpdatedUri();
1062 updatedUri
.extend( params
|| {} );
1065 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1066 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1068 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1073 * Get an updated mw.Uri object based on the model state
1075 * @return {mw.Uri} Updated Uri
1077 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1078 var uri
= new mw
.Uri();
1081 uri
.query
= this.uriProcessor
.minimizeQuery(
1085 // We want to retain unrecognized params
1086 // The uri params from model will override
1087 // any recognized value in the current uri
1088 // query, retain unrecognized params, and
1089 // the result will then be minimized
1091 this.uriProcessor
.getUriParametersFromModel(),
1100 * Fetch the list of changes from the server for the current filters
1102 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1103 * not to invalidate each other.
1104 * @param {Object} [params={}] Parameters to add to the query
1106 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1107 * or with a string denoting no results.
1109 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function ( counterId
, params
) {
1110 var uri
= this._getUpdatedUri(),
1111 stickyParams
= this.filtersModel
.getStickyParams(),
1115 counterId
= counterId
|| 'updateChangesList';
1116 params
= params
|| {};
1118 uri
.extend( params
);
1120 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1121 requestId
= ++this.requestCounter
[ counterId
];
1122 latestRequest = function () {
1123 return requestId
=== this.requestCounter
[ counterId
];
1126 // Sticky parameters override the URL params
1127 // this is to make sure that whether we represent
1128 // the sticky params in the URL or not (they may
1129 // be normalized out) the sticky parameters are
1130 // always being sent to the server with their
1131 // current/default values
1132 uri
.extend( stickyParams
);
1134 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1139 if ( !latestRequest() ) {
1140 return $.Deferred().reject();
1143 $parsed
= $( $.parseHTML( html
) );
1147 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1149 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1153 function ( responseObj
) {
1156 if ( !latestRequest() ) {
1157 return $.Deferred().reject();
1160 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
1162 // Force a resolve state to this promise
1163 return $.Deferred().resolve( {
1164 changes
: 'NO_RESULTS',
1165 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1172 * Track usage of highlight feature
1174 * @param {string} action
1175 * @param {Array|Object|string} filters
1177 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1178 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1179 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1181 'event.ChangesListHighlights',
1185 userId
: mw
.user
.getId()
1191 * Track filter grouping usage
1193 * @param {string} action Action taken
1195 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1196 var controller
= this,
1197 rightNow
= new Date().getTime(),
1198 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1199 // Get all current filters
1200 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1201 return item
.getName();
1204 action
= action
|| 'filtermenu';
1206 // Check if these filters were the ones we just logged previously
1207 // (Don't log the same grouping twice, in case the user opens/closes)
1208 // the menu without action, or with the same result
1210 // Only log if the two arrays are different in size
1211 filters
.length
!== this.prevLoggedItems
.length
||
1212 // Or if any filters are not the same as the cached filters
1213 filters
.some( function ( filterName
) {
1214 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1216 // Or if any cached filters are not the same as given filters
1217 this.prevLoggedItems
.some( function ( filterName
) {
1218 return filters
.indexOf( filterName
) === -1;
1221 filters
.forEach( function ( filterName
) {
1223 'event.ChangesListFilterGrouping',
1226 groupIdentifier
: randomIdentifier
,
1228 userId
: mw
.user
.getId()
1233 // Cache the filter names
1234 this.prevLoggedItems
= filters
;
1237 }( mediaWiki
, jQuery
) );