4051edaabf9dbb90823334fdd110dc2a430e8d5d
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
),
109 filters
: [ 50, 100, 250, 500 ].map( function ( num
) {
110 return controller
._createFilterDataFromNumber( num
, num
);
115 type
: 'single_option',
116 title
: '', // Because it's a hidden group, this title actually appears nowhere
118 allowArbitrary
: true,
119 validate
: $.isNumeric
,
120 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
121 numToLabelFunc: function ( i
) {
122 return Number( i
) < 1 ?
123 ( Number( i
) * 24 ).toFixed( 2 ) :
126 'default': mw
.user
.options
.get( 'rcdays', '30' ),
129 // Hours (1, 2, 6, 12)
130 0.04166, 0.0833, 0.25, 0.5,
133 ].map( function ( num
) {
134 return controller
._createFilterDataFromNumber(
136 // Convert fractions of days to number of hours for the labels
137 num
< 1 ? Math
.round( num
* 24 ) : num
144 // Before we do anything, we need to see if we require additional items in the
145 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
146 // groups; if we ever expand it, this might need further generalization:
147 $.each( views
, function ( viewName
, viewData
) {
148 viewData
.groups
.forEach( function ( groupData
) {
149 var extraValues
= [];
150 if ( groupData
.allowArbitrary
) {
151 // If the value in the URI isn't in the group, add it
152 if ( uri
.query
[ groupData
.name
] !== undefined ) {
153 extraValues
.push( uri
.query
[ groupData
.name
] );
155 // If the default value isn't in the group, add it
156 if ( groupData
.default !== undefined ) {
157 extraValues
.push( String( groupData
.default ) );
159 controller
.addNumberValuesToGroup( groupData
, extraValues
);
164 // Initialize the model
165 this.filtersModel
.initializeFilters( filterStructure
, views
);
167 this._buildBaseFilterState();
169 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
174 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
176 parsedSavedQueries
= {};
179 // The queries are saved in a minimized state, so we need
180 // to send over the base state so the saved queries model
181 // can normalize them per each query item
182 this.savedQueriesModel
.initialize(
184 this._getBaseFilterState(),
185 // This is for backwards compatibility - delete all sticky filter states
186 Object
.keys( this.filtersModel
.getStickyFiltersState() )
189 // Check whether we need to load defaults.
190 // We do this by checking whether the current URI query
191 // contains any parameters recognized by the system.
192 // If it does, we load the given state.
193 // If it doesn't, we have no values at all, and we assume
194 // the user loads the base-page and we load defaults.
195 // Defaults should only be applied on load (if necessary)
197 this.initializing
= true;
199 this.savedQueriesModel
.getDefault() &&
200 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
202 // We have defaults from a saved query.
203 // We will load them straight-forward (as if
204 // they were clicked in the menu) so we trigger
205 // a full ajax request and change of URL
206 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
208 // There are either recognized parameters in the URL
209 // or there are none, but there is also no default
210 // saved query (so defaults are from the backend)
211 // We want to update the state but not fetch results
213 this.updateStateFromUrl( false );
215 // Update the changes list with the existing data
216 // so it gets processed
217 this.changesListModel
.update(
218 $changesList
.length
? $changesList
: 'NO_RESULTS',
219 $( 'fieldset.rcoptions' ).first(),
220 true // We're using existing DOM elements
224 this.initializing
= false;
225 this.switchView( 'default' );
227 this._scheduleLiveUpdate();
231 * Create filter data from a number, for the filters that are numerical value
233 * @param {Number} num Number
234 * @param {Number} numForDisplay Number for the label
235 * @return {Object} Filter data
237 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
240 label
: mw
.language
.convertNumber( numForDisplay
)
245 * Add an arbitrary values to groups that allow arbitrary values
247 * @param {Object} groupData Group data
248 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
250 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
251 var controller
= this;
253 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
255 // This is only true for single_option group
256 // We assume these are the only groups that will allow for
257 // arbitrary, since it doesn't make any sense for the other
259 arbitraryValues
.forEach( function ( val
) {
261 // If the group allows for arbitrary data
262 groupData
.allowArbitrary
&&
263 // and it is single_option (or string_options, but we
264 // don't have cases of those yet, nor do we plan to)
265 groupData
.type
=== 'single_option' &&
266 // and, if there is a validate method and it passes on
268 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
269 // but if that value isn't already in the definition
271 .map( function ( filterData
) {
272 return filterData
.name
;
274 .indexOf( val
) === -1
276 // Add the filter information
277 groupData
.filters
.push( controller
._createFilterDataFromNumber(
279 groupData
.numToLabelFunc
?
280 groupData
.numToLabelFunc( val
) :
284 // If there's a sort function set up, re-sort the values
285 if ( groupData
.sortFunc
) {
286 groupData
.filters
.sort( groupData
.sortFunc
);
293 * Switch the view of the filters model
295 * @param {string} view Requested view
297 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
298 this.filtersModel
.switchView( view
);
302 * Reset to default filters
304 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
305 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
307 this.updateChangesList();
311 * Empty all selected filters
313 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
314 var highlightedFilterNames
= this.filtersModel
315 .getHighlightedItems()
316 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
318 this.filtersModel
.emptyAllFilters();
319 this.filtersModel
.clearAllHighlightColors();
320 // Check all filter interactions
321 this.filtersModel
.reassessFilterInteractions();
323 this.updateChangesList();
325 if ( highlightedFilterNames
) {
326 this._trackHighlight( 'clearAll', highlightedFilterNames
);
331 * Update the selected state of a filter
333 * @param {string} filterName Filter name
334 * @param {boolean} [isSelected] Filter selected state
336 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
337 var filterItem
= this.filtersModel
.getItemByName( filterName
);
340 // If no filter was found, break
344 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
346 if ( filterItem
.isSelected() !== isSelected
) {
347 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
349 this.updateChangesList();
351 // Check filter interactions
352 this.filtersModel
.reassessFilterInteractions( filterItem
);
357 * Clear both highlight and selection of a filter
359 * @param {string} filterName Name of the filter item
361 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
362 var filterItem
= this.filtersModel
.getItemByName( filterName
),
363 isHighlighted
= filterItem
.isHighlighted();
365 if ( filterItem
.isSelected() || isHighlighted
) {
366 this.filtersModel
.clearHighlightColor( filterName
);
367 this.filtersModel
.toggleFilterSelected( filterName
, false );
368 this.updateChangesList();
369 this.filtersModel
.reassessFilterInteractions( filterItem
);
371 // Log filter grouping
372 this.trackFilterGroupings( 'removefilter' );
375 if ( isHighlighted
) {
376 this._trackHighlight( 'clear', filterName
);
381 * Toggle the highlight feature on and off
383 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
384 this.filtersModel
.toggleHighlight();
387 if ( this.filtersModel
.isHighlightEnabled() ) {
388 mw
.hook( 'RcFilters.highlight.enable' ).fire();
393 * Toggle the namespaces inverted feature on and off
395 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
396 this.filtersModel
.toggleInvertedNamespaces();
397 this.updateChangesList();
401 * Set the highlight color for a filter item
403 * @param {string} filterName Name of the filter item
404 * @param {string} color Selected color
406 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
407 this.filtersModel
.setHighlightColor( filterName
, color
);
409 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
413 * Clear highlight for a filter item
415 * @param {string} filterName Name of the filter item
417 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
418 this.filtersModel
.clearHighlightColor( filterName
);
420 this._trackHighlight( 'clear', filterName
);
424 * Enable or disable live updates.
425 * @param {boolean} enable True to enable, false to disable
427 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
428 this.changesListModel
.toggleLiveUpdate( enable
);
429 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
430 this.showNewChanges();
435 * Set a timeout for the next live update.
438 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
439 setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
443 * Perform a live update.
446 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
447 if ( !this._shouldCheckForNewChanges() ) {
448 // skip this turn and check back later
449 this._scheduleLiveUpdate();
453 this._checkForNewChanges()
454 .then( function ( data
) {
455 if ( !this._shouldCheckForNewChanges() ) {
456 // by the time the response is received,
457 // it may not be appropriate anymore
461 if ( data
.changes
!== 'NO_RESULTS' ) {
462 if ( this.changesListModel
.getLiveUpdate() ) {
463 return this.updateChangesList( false, null, true, false );
465 this.changesListModel
.setNewChangesExist( true );
469 .always( this._scheduleLiveUpdate
.bind( this ) );
473 * @return {boolean} It's appropriate to check for new changes now
476 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
477 var liveUpdateFeatureFlag
= mw
.config
.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
478 new mw
.Uri().query
.liveupdate
;
480 return !document
.hidden
&&
481 !this.changesListModel
.getNewChangesExist() &&
482 !this.updatingChangesList
&&
483 liveUpdateFeatureFlag
;
487 * Check if new changes, newer than those currently shown, are available
489 * @return {jQuery.Promise} Promise object that resolves after trying
490 * to fetch 1 change newer than the last known 'from' parameter value
494 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
495 return this._fetchChangesList(
499 from: this.changesListModel
.getNextFrom()
505 * Show the new changes
507 * @return {jQuery.Promise} Promise object that resolves after
508 * fetching and showing the new changes
510 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
511 return this.updateChangesList( false, null, true, true );
515 * Save the current model state as a saved query
517 * @param {string} [label] Label of the saved query
518 * @param {boolean} [setAsDefault=false] This query should be set as the default
520 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
522 highlightedItems
= {},
523 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
524 selectedState
= this.filtersModel
.getSelectedState();
526 // Prepare highlights
527 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
528 highlightedItems
[ item
.getName() ] = highlightEnabled
?
529 item
.getHighlightColor() : null;
531 // These are filter states; highlight is stored as boolean
532 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
534 // Delete all sticky filters
535 this._deleteStickyValuesFromFilterState( selectedState
);
538 queryID
= this.savedQueriesModel
.addNewQuery(
539 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
541 filters
: selectedState
,
542 highlights
: highlightedItems
,
543 invert
: this.filtersModel
.areNamespacesInverted()
547 if ( setAsDefault
) {
548 this.savedQueriesModel
.setDefault( queryID
);
552 this._saveSavedQueries();
556 * Remove a saved query
558 * @param {string} queryID Query id
560 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
561 this.savedQueriesModel
.removeQuery( queryID
);
563 this._saveSavedQueries();
567 * Rename a saved query
569 * @param {string} queryID Query id
570 * @param {string} newLabel New label for the query
572 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
573 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
576 queryItem
.updateLabel( newLabel
);
578 this._saveSavedQueries();
582 * Set a saved query as default
584 * @param {string} queryID Query Id. If null is given, default
587 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
588 this.savedQueriesModel
.setDefault( queryID
);
589 this._saveSavedQueries();
595 * @param {string} queryID Query id
597 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
598 var data
, highlights
,
599 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
602 data
= queryItem
.getData();
603 highlights
= data
.highlights
;
605 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
606 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
608 // Update model state from filters
609 this.filtersModel
.toggleFiltersSelected(
610 // Merge filters with sticky values
611 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
614 // Update namespace inverted property
615 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
617 // Update highlight state
618 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
619 this.filtersModel
.getItems().forEach( function ( filterItem
) {
620 var color
= highlights
[ filterItem
.getName() ];
622 filterItem
.setHighlightColor( color
);
624 filterItem
.clearHighlightColor();
628 // Check all filter interactions
629 this.filtersModel
.reassessFilterInteractions();
631 this.updateChangesList();
633 // Log filter grouping
634 this.trackFilterGroupings( 'savedfilters' );
639 * Check whether the current filter and highlight state exists
640 * in the saved queries model.
642 * @return {boolean} Query exists
644 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
645 var highlightedItems
= {},
646 selectedState
= this.filtersModel
.getSelectedState();
648 // Prepare highlights of the current query
649 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
650 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
652 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
654 // Remove sticky filters
655 this._deleteStickyValuesFromFilterState( selectedState
);
657 return this.savedQueriesModel
.findMatchingQuery(
659 filters
: selectedState
,
660 highlights
: highlightedItems
,
661 invert
: this.filtersModel
.areNamespacesInverted()
667 * Delete sticky filters from given object
669 * @param {Object} filterState Filter state
671 mw
.rcfilters
.Controller
.prototype._deleteStickyValuesFromFilterState = function ( filterState
) {
672 // Remove sticky filters
673 $.each( this.filtersModel
.getStickyFiltersState(), function ( filterName
) {
674 delete filterState
[ filterName
];
679 * Get an object representing the base state of parameters
682 * This is meant to make sure that the saved queries that are
683 * in memory are always the same structure as what we would get
684 * by calling the current model's "getSelectedState" and by checking
687 * In cases where a user saved a query when the system had a certain
688 * set of filters, and then a filter was added to the system, we want
689 * to make sure that the stored queries can still be comparable to
690 * the current state, which means that we need the base state for
693 * - Saved queries are stored in "minimal" view (only changed filters
694 * are stored); When we initialize the system, we merge each minimal
695 * query with the base state (using 'getNormalizedFilters') so all
696 * saved queries have the exact same structure as what we would get
697 * by checking the getSelectedState of the filter.
698 * - When we save the queries, we minimize the object to only represent
699 * whatever has actually changed, rather than store the entire
700 * object. To check what actually is different so we can store it,
701 * we need to obtain a base state to compare against, this is
702 * what #_getMinimalFilterList does
704 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
705 var defaultParams
= this.filtersModel
.getDefaultParams(),
706 highlightedItems
= {};
708 // Prepare highlights
709 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
710 highlightedItems
[ item
.getName() ] = null;
712 highlightedItems
.highlight
= false;
714 this.baseFilterState
= {
715 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
716 highlights
: highlightedItems
,
722 * Get an object representing the base filter state of both
723 * filters and highlights. The structure is similar to what we use
724 * to store each query in the saved queries object:
730 * filterName: (string|null)
734 * @return {Object} Object representing the base state of
735 * parameters and highlights
737 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
738 return this.baseFilterState
;
742 * Get an object that holds only the parameters and highlights that have
743 * values different than the base default value.
745 * This is the reverse of the normalization we do initially on loading and
746 * initializing the saved queries model.
748 * @param {Object} valuesObject Object representing the state of both
749 * filters and highlights in its normalized version, to be minimized.
750 * @return {Object} Minimal filters and highlights list
752 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
753 var result
= { filters
: {}, highlights
: {} },
754 baseState
= this._getBaseFilterState();
757 $.each( valuesObject
.filters
, function ( name
, value
) {
758 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
759 result
.filters
[ name
] = value
;
763 $.each( valuesObject
.highlights
, function ( name
, value
) {
764 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
765 result
.highlights
[ name
] = value
;
773 * Save the current state of the saved queries model with all
774 * query item representation in the user settings.
776 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
778 state
= this.savedQueriesModel
.getState(),
781 // Minimize before save
782 $.each( state
.queries
, function ( queryID
, info
) {
783 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
787 stringified
= JSON
.stringify( state
);
789 if ( stringified
.length
> 65535 ) {
790 // Sanity check, since the preference can only hold that.
794 // Save the preference
795 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
796 // Update the preference for this session
797 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
801 * Update sticky preferences with current model state
803 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
804 // Update default sticky values with selected, whether they came from
805 // the initial defaults or from the URL value that is being normalized
806 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
807 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
811 * Update the limit default value
813 * @param {number} newValue New value
815 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
816 if ( !$.isNumeric( newValue
) ) {
820 newValue
= Number( newValue
);
822 if ( mw
.user
.options
.get( 'rcfilters-rclimit' ) !== newValue
) {
823 // Save the preference
824 new mw
.Api().saveOption( 'rcfilters-rclimit', newValue
);
825 // Update the preference for this session
826 mw
.user
.options
.set( 'rcfilters-rclimit', newValue
);
831 * Update the days default value
833 * @param {number} newValue New value
835 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
836 if ( !$.isNumeric( newValue
) ) {
840 newValue
= Number( newValue
);
842 if ( mw
.user
.options
.get( 'rcdays' ) !== newValue
) {
843 // Save the preference
844 new mw
.Api().saveOption( 'rcdays', newValue
);
845 // Update the preference for this session
846 mw
.user
.options
.set( 'rcdays', newValue
);
851 * Synchronize the URL with the current state of the filters
852 * without adding an history entry.
854 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
855 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
859 * Update filter state (selection and highlighting) based
860 * on current URL values.
862 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
863 * list based on the updated model.
865 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
866 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
868 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
870 // Update the sticky preferences, in case we received a value
872 this.updateStickyPreferences();
874 // Only update and fetch new results if it is requested
875 if ( fetchChangesList
) {
876 this.updateChangesList();
881 * Update the list of changes and notify the model
883 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
884 * @param {Object} [params] Extra parameters to add to the API call
885 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
886 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
887 * @return {jQuery.Promise} Promise that is resolved when the update is complete
889 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( updateUrl
, params
, isLiveUpdate
, invalidateCurrentChanges
) {
890 updateUrl
= updateUrl
=== undefined ? true : updateUrl
;
891 invalidateCurrentChanges
= invalidateCurrentChanges
=== undefined ? true : invalidateCurrentChanges
;
893 this._updateURL( params
);
895 if ( invalidateCurrentChanges
) {
896 this.changesListModel
.invalidate();
898 this.changesListModel
.setNewChangesExist( false );
899 this.updatingChangesList
= true;
900 return this._fetchChangesList()
903 function ( pieces
) {
904 var $changesListContent
= pieces
.changes
,
905 $fieldset
= pieces
.fieldset
;
906 this.changesListModel
.update( $changesListContent
, $fieldset
, false, isLiveUpdate
);
908 // Do nothing for failure
910 .always( function () {
911 this.updatingChangesList
= false;
916 * Get an object representing the default parameter state, whether
917 * it is from the model defaults or from the saved queries.
919 * @return {Object} Default parameters
921 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
922 var data
, queryHighlights
,
924 savedHighlights
= {},
925 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
927 if ( defaultSavedQueryItem
) {
928 data
= defaultSavedQueryItem
.getData();
930 queryHighlights
= data
.highlights
|| {};
931 savedParams
= this.filtersModel
.getParametersFromFilters(
932 // Merge filters with sticky values
933 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
936 // Translate highlights to parameters
937 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
938 $.each( queryHighlights
, function ( filterName
, color
) {
939 if ( filterName
!== 'highlights' ) {
940 savedHighlights
[ filterName
+ '_color' ] = color
;
944 return $.extend( true, {}, savedParams
, savedHighlights
);
947 return this.filtersModel
.getDefaultParams();
951 * Update the URL of the page to reflect current filters
953 * This should not be called directly from outside the controller.
954 * If an action requires changing the URL, it should either use the
955 * highlighting actions below, or call #updateChangesList which does
956 * the uri corrections already.
958 * @param {Object} [params] Extra parameters to add to the API call
960 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
961 var currentUri
= new mw
.Uri(),
962 updatedUri
= this._getUpdatedUri();
964 updatedUri
.extend( params
|| {} );
967 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
968 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
970 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
975 * Get an updated mw.Uri object based on the model state
977 * @return {mw.Uri} Updated Uri
979 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
980 var uri
= new mw
.Uri();
983 uri
.query
= this.uriProcessor
.minimizeQuery(
987 // We want to retain unrecognized params
988 // The uri params from model will override
989 // any recognized value in the current uri
990 // query, retain unrecognized params, and
991 // the result will then be minimized
993 this.uriProcessor
.getUriParametersFromModel(),
1002 * Fetch the list of changes from the server for the current filters
1004 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1005 * not to invalidate each other.
1006 * @param {Object} [params={}] Parameters to add to the query
1008 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1009 * or with a string denoting no results.
1011 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function ( counterId
, params
) {
1012 var uri
= this._getUpdatedUri(),
1013 stickyParams
= this.filtersModel
.getStickyParams(),
1017 counterId
= counterId
|| 'updateChangesList';
1018 params
= params
|| {};
1020 uri
.extend( params
);
1022 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1023 requestId
= ++this.requestCounter
[ counterId
];
1024 latestRequest = function () {
1025 return requestId
=== this.requestCounter
[ counterId
];
1028 // Sticky parameters override the URL params
1029 // this is to make sure that whether we represent
1030 // the sticky params in the URL or not (they may
1031 // be normalized out) the sticky parameters are
1032 // always being sent to the server with their
1033 // current/default values
1034 uri
.extend( stickyParams
);
1036 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1041 if ( !latestRequest() ) {
1042 return $.Deferred().reject();
1045 $parsed
= $( $.parseHTML( html
) );
1049 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1051 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1055 function ( responseObj
) {
1058 if ( !latestRequest() ) {
1059 return $.Deferred().reject();
1062 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
1064 // Force a resolve state to this promise
1065 return $.Deferred().resolve( {
1066 changes
: 'NO_RESULTS',
1067 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1074 * Track usage of highlight feature
1076 * @param {string} action
1077 * @param {Array|Object|string} filters
1079 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1080 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1081 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1083 'event.ChangesListHighlights',
1087 userId
: mw
.user
.getId()
1093 * Track filter grouping usage
1095 * @param {string} action Action taken
1097 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1098 var controller
= this,
1099 rightNow
= new Date().getTime(),
1100 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1101 // Get all current filters
1102 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1103 return item
.getName();
1106 action
= action
|| 'filtermenu';
1108 // Check if these filters were the ones we just logged previously
1109 // (Don't log the same grouping twice, in case the user opens/closes)
1110 // the menu without action, or with the same result
1112 // Only log if the two arrays are different in size
1113 filters
.length
!== this.prevLoggedItems
.length
||
1114 // Or if any filters are not the same as the cached filters
1115 filters
.some( function ( filterName
) {
1116 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1118 // Or if any cached filters are not the same as given filters
1119 this.prevLoggedItems
.some( function ( filterName
) {
1120 return filters
.indexOf( filterName
) === -1;
1123 filters
.forEach( function ( filterName
) {
1125 'event.ChangesListFilterGrouping',
1128 groupIdentifier
: randomIdentifier
,
1130 userId
: mw
.user
.getId()
1135 // Cache the filter names
1136 this.prevLoggedItems
= filters
;
1139 }( mediaWiki
, jQuery
) );