2 /* eslint no-underscore-dangle: "off" */
4 * Controller for the filters in Recent Changes
8 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
9 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
10 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
11 * @param {Object} config Additional configuration
12 * @cfg {string} savedQueriesPreferenceName Where to save the saved queries
13 * @cfg {string} daysPreferenceName Preference name for the days filter
14 * @cfg {string} limitPreferenceName Preference name for the limit filter
16 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
, config
) {
17 this.filtersModel
= filtersModel
;
18 this.changesListModel
= changesListModel
;
19 this.savedQueriesModel
= savedQueriesModel
;
20 this.savedQueriesPreferenceName
= config
.savedQueriesPreferenceName
;
21 this.daysPreferenceName
= config
.daysPreferenceName
;
22 this.limitPreferenceName
= config
.limitPreferenceName
;
24 this.requestCounter
= {};
25 this.baseFilterState
= {};
26 this.uriProcessor
= null;
27 this.initializing
= false;
28 this.wereSavedQueriesSaved
= false;
30 this.prevLoggedItems
= [];
32 this.FILTER_CHANGE
= 'filterChange';
33 this.SHOW_NEW_CHANGES
= 'showNewChanges';
34 this.LIVE_UPDATE
= 'liveUpdate';
38 OO
.initClass( mw
.rcfilters
.Controller
);
41 * Initialize the filter and parameter states
43 * @param {Array} filterStructure Filter definition and structure for the model
44 * @param {Object} [namespaceStructure] Namespace definition
45 * @param {Object} [tagList] Tag definition
46 * @param {Object} [conditionalViews] Conditional view definition
48 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
, conditionalViews
) {
49 var parsedSavedQueries
, pieces
,
50 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
51 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
53 views
= $.extend( true, {}, conditionalViews
),
58 if ( namespaceStructure
) {
60 $.each( namespaceStructure
, function ( namespaceID
, label
) {
61 // Build and clean up the individual namespace items definition
64 label
: label
|| mw
.msg( 'blanknamespace' ),
67 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
70 cssClass
: 'mw-changeslist-ns-' + namespaceID
75 title
: mw
.msg( 'namespaces' ),
78 // Group definition (single group)
79 name
: 'namespace', // parameter name is singular
80 type
: 'string_options',
81 title
: mw
.msg( 'namespaces' ),
82 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
103 title
: mw
.msg( 'rcfilters-view-tags' ),
106 // Group definition (single group)
107 name
: 'tagfilter', // Parameter name
108 type
: 'string_options',
109 title
: 'rcfilters-view-tags', // Message key
110 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
118 // Add parameter range operations
123 type
: 'single_option',
124 title
: '', // Because it's a hidden group, this title actually appears nowhere
126 allowArbitrary
: true,
127 validate
: $.isNumeric
,
129 min
: 0, // The server normalizes negative numbers to 0 results
132 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
133 'default': mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
135 filters
: displayConfig
.limitArray
.map( function ( num
) {
136 return controller
._createFilterDataFromNumber( num
, num
);
141 type
: 'single_option',
142 title
: '', // Because it's a hidden group, this title actually appears nowhere
144 allowArbitrary
: true,
145 validate
: $.isNumeric
,
148 max
: displayConfig
.maxDays
150 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
151 numToLabelFunc: function ( i
) {
152 return Number( i
) < 1 ?
153 ( Number( i
) * 24 ).toFixed( 2 ) :
156 'default': mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
159 // Hours (1, 2, 6, 12)
160 0.04166, 0.0833, 0.25, 0.5
162 ].concat( displayConfig
.daysArray
)
163 .map( function ( num
) {
164 return controller
._createFilterDataFromNumber(
166 // Convert fractions of days to number of hours for the labels
167 num
< 1 ? Math
.round( num
* 24 ) : num
179 title
: '', // Because it's a hidden group, this title actually appears nowhere
185 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
192 // Before we do anything, we need to see if we require additional items in the
193 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
194 // groups; if we ever expand it, this might need further generalization:
195 $.each( views
, function ( viewName
, viewData
) {
196 viewData
.groups
.forEach( function ( groupData
) {
197 var extraValues
= [];
198 if ( groupData
.allowArbitrary
) {
199 // If the value in the URI isn't in the group, add it
200 if ( uri
.query
[ groupData
.name
] !== undefined ) {
201 extraValues
.push( uri
.query
[ groupData
.name
] );
203 // If the default value isn't in the group, add it
204 if ( groupData
.default !== undefined ) {
205 extraValues
.push( String( groupData
.default ) );
207 controller
.addNumberValuesToGroup( groupData
, extraValues
);
212 // Initialize the model
213 this.filtersModel
.initializeFilters( filterStructure
, views
);
215 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
219 if ( !mw
.user
.isAnon() ) {
221 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
223 parsedSavedQueries
= {};
226 // Initialize saved queries
227 this.savedQueriesModel
.initialize( parsedSavedQueries
);
228 if ( this.savedQueriesModel
.isConverted() ) {
229 // Since we know we converted, we're going to re-save
230 // the queries so they are now migrated to the new format
231 this._saveSavedQueries();
235 // Check whether we need to load defaults.
236 // We do this by checking whether the current URI query
237 // contains any parameters recognized by the system.
238 // If it does, we load the given state.
239 // If it doesn't, we have no values at all, and we assume
240 // the user loads the base-page and we load defaults.
241 // Defaults should only be applied on load (if necessary)
243 this.initializing
= true;
245 if ( defaultSavedQueryExists
) {
246 // This came from the server, meaning that we have a default
247 // saved query, but the server could not load it, probably because
248 // it was pre-conversion to the new format.
249 // We need to load this query again
250 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
252 // There are either recognized parameters in the URL
253 // or there are none, but there is also no default
254 // saved query (so defaults are from the backend)
255 // We want to update the state but not fetch results
257 this.updateStateFromUrl( false );
259 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
261 // Update the changes list with the existing data
262 // so it gets processed
263 this.changesListModel
.update(
266 pieces
.noResultsDetails
,
267 true // We're using existing DOM elements
271 this.initializing
= false;
272 this.switchView( 'default' );
274 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
275 if ( this.pollingRate
) {
276 this._scheduleLiveUpdate();
281 * Extracts information from the changes list DOM
283 * @param {jQuery} $root Root DOM to find children from
284 * @param {boolean} [statusCode] Server response status code
285 * @return {Object} Information about changes list
286 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
287 * (either normally or as an error)
288 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
289 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
290 * @return {jQuery} return.fieldset Fieldset
292 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
, statusCode
) {
294 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
295 areResults
= !!$changesListContents
.length
,
296 checkForLogout
= !areResults
&& statusCode
=== 200;
298 // We check if user logged out on different tab/browser or the session has expired.
299 // 205 status code returned from the server, which indicates that we need to reload the page
300 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
301 // status code (if everything else goes well).
303 if ( checkForLogout
&& !!$root
.find( '#wpName1' ).length
) {
304 location
.reload( false );
309 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
310 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
314 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
315 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
316 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
317 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
319 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
327 * Create filter data from a number, for the filters that are numerical value
329 * @param {Number} num Number
330 * @param {Number} numForDisplay Number for the label
331 * @return {Object} Filter data
333 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
336 label
: mw
.language
.convertNumber( numForDisplay
)
341 * Add an arbitrary values to groups that allow arbitrary values
343 * @param {Object} groupData Group data
344 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
346 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
347 var controller
= this,
348 normalizeWithinRange = function ( range
, val
) {
349 if ( val
< range
.min
) {
350 return range
.min
; // Min
351 } else if ( val
>= range
.max
) {
352 return range
.max
; // Max
357 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
359 // Normalize the arbitrary values and the default value for a range
360 if ( groupData
.range
) {
361 arbitraryValues
= arbitraryValues
.map( function ( val
) {
362 return normalizeWithinRange( groupData
.range
, val
);
365 // Normalize the default, since that's user defined
366 if ( groupData
.default !== undefined ) {
367 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
371 // This is only true for single_option group
372 // We assume these are the only groups that will allow for
373 // arbitrary, since it doesn't make any sense for the other
375 arbitraryValues
.forEach( function ( val
) {
377 // If the group allows for arbitrary data
378 groupData
.allowArbitrary
&&
379 // and it is single_option (or string_options, but we
380 // don't have cases of those yet, nor do we plan to)
381 groupData
.type
=== 'single_option' &&
382 // and, if there is a validate method and it passes on
384 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
385 // but if that value isn't already in the definition
387 .map( function ( filterData
) {
388 return String( filterData
.name
);
390 .indexOf( String( val
) ) === -1
392 // Add the filter information
393 groupData
.filters
.push( controller
._createFilterDataFromNumber(
395 groupData
.numToLabelFunc
?
396 groupData
.numToLabelFunc( val
) :
400 // If there's a sort function set up, re-sort the values
401 if ( groupData
.sortFunc
) {
402 groupData
.filters
.sort( groupData
.sortFunc
);
409 * Reset to default filters
411 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
412 var params
= this._getDefaultParams();
413 if ( this.applyParamChange( params
) ) {
414 // Only update the changes list if there was a change to actual filters
415 this.updateChangesList();
417 this.uriProcessor
.updateURL( params
);
422 * Check whether the default values of the filters are all false.
424 * @return {boolean} Defaults are all false
426 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
427 return $.isEmptyObject( this._getDefaultParams() );
431 * Empty all selected filters
433 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
434 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
435 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
437 if ( this.applyParamChange( {} ) ) {
438 // Only update the changes list if there was a change to actual filters
439 this.updateChangesList();
441 this.uriProcessor
.updateURL();
444 if ( highlightedFilterNames
) {
445 this._trackHighlight( 'clearAll', highlightedFilterNames
);
450 * Update the selected state of a filter
452 * @param {string} filterName Filter name
453 * @param {boolean} [isSelected] Filter selected state
455 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
456 var filterItem
= this.filtersModel
.getItemByName( filterName
);
459 // If no filter was found, break
463 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
465 if ( filterItem
.isSelected() !== isSelected
) {
466 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
468 this.updateChangesList();
470 // Check filter interactions
471 this.filtersModel
.reassessFilterInteractions( filterItem
);
476 * Clear both highlight and selection of a filter
478 * @param {string} filterName Name of the filter item
480 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
481 var filterItem
= this.filtersModel
.getItemByName( filterName
),
482 isHighlighted
= filterItem
.isHighlighted(),
483 isSelected
= filterItem
.isSelected();
485 if ( isSelected
|| isHighlighted
) {
486 this.filtersModel
.clearHighlightColor( filterName
);
487 this.filtersModel
.toggleFilterSelected( filterName
, false );
490 // Only update the changes list if the filter changed
491 // its selection state. If it only changed its highlight
493 this.updateChangesList();
496 this.filtersModel
.reassessFilterInteractions( filterItem
);
498 // Log filter grouping
499 this.trackFilterGroupings( 'removefilter' );
502 if ( isHighlighted
) {
503 this._trackHighlight( 'clear', filterName
);
508 * Toggle the highlight feature on and off
510 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
511 this.filtersModel
.toggleHighlight();
512 this.uriProcessor
.updateURL();
514 if ( this.filtersModel
.isHighlightEnabled() ) {
515 mw
.hook( 'RcFilters.highlight.enable' ).fire();
520 * Toggle the namespaces inverted feature on and off
522 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
523 this.filtersModel
.toggleInvertedNamespaces();
525 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
526 function ( filterItem
) { return filterItem
.isSelected(); }
529 // Only re-fetch results if there are namespace items that are actually selected
530 this.updateChangesList();
532 this.uriProcessor
.updateURL();
537 * Set the value of the 'showlinkedto' parameter
538 * @param {boolean} value
540 mw
.rcfilters
.Controller
.prototype.setShowLinkedTo = function ( value
) {
541 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
542 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
544 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
545 this.uriProcessor
.updateURL();
546 // reload the results only when target is set
547 if ( targetItem
.getValue() ) {
548 this.updateChangesList();
553 * Set the target page
554 * @param {string} page
556 mw
.rcfilters
.Controller
.prototype.setTargetPage = function ( page
) {
557 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
558 targetItem
.setValue( page
);
559 this.uriProcessor
.updateURL();
560 this.updateChangesList();
564 * Set the highlight color for a filter item
566 * @param {string} filterName Name of the filter item
567 * @param {string} color Selected color
569 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
570 this.filtersModel
.setHighlightColor( filterName
, color
);
571 this.uriProcessor
.updateURL();
572 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
576 * Clear highlight for a filter item
578 * @param {string} filterName Name of the filter item
580 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
581 this.filtersModel
.clearHighlightColor( filterName
);
582 this.uriProcessor
.updateURL();
583 this._trackHighlight( 'clear', filterName
);
587 * Enable or disable live updates.
588 * @param {boolean} enable True to enable, false to disable
590 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
591 this.changesListModel
.toggleLiveUpdate( enable
);
592 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
593 this.updateChangesList( null, this.LIVE_UPDATE
);
598 * Set a timeout for the next live update.
601 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
602 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
606 * Perform a live update.
609 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
610 if ( !this._shouldCheckForNewChanges() ) {
611 // skip this turn and check back later
612 this._scheduleLiveUpdate();
616 this._checkForNewChanges()
617 .then( function ( statusCode
) {
618 // no result is 204 with the 'peek' param
620 var newChanges
= statusCode
=== 200;
622 if ( !this._shouldCheckForNewChanges() ) {
623 // by the time the response is received,
624 // it may not be appropriate anymore
628 // 205 is the status code returned from server when user's logged in/out
629 // status is not matching while fetching live update changes.
630 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
632 if ( statusCode
=== 205 ) {
633 location
.reload( false );
638 if ( this.changesListModel
.getLiveUpdate() ) {
639 return this.updateChangesList( null, this.LIVE_UPDATE
);
641 this.changesListModel
.setNewChangesExist( true );
645 .always( this._scheduleLiveUpdate
.bind( this ) );
649 * @return {boolean} It's appropriate to check for new changes now
652 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
653 return !document
.hidden
&&
654 !this.filtersModel
.hasConflict() &&
655 !this.changesListModel
.getNewChangesExist() &&
656 !this.updatingChangesList
&&
657 this.changesListModel
.getNextFrom();
661 * Check if new changes, newer than those currently shown, are available
663 * @return {jQuery.Promise} Promise object that resolves with a bool
664 * specifying if there are new changes or not
668 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
671 peek
: 1, // bypasses ChangesList specific UI
672 from: this.changesListModel
.getNextFrom(),
673 isAnon
: mw
.user
.isAnon()
675 return this._queryChangesList( 'liveUpdate', params
).then(
683 * Show the new changes
685 * @return {jQuery.Promise} Promise object that resolves after
686 * fetching and showing the new changes
688 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
689 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
693 * Save the current model state as a saved query
695 * @param {string} [label] Label of the saved query
696 * @param {boolean} [setAsDefault=false] This query should be set as the default
698 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
700 this.savedQueriesModel
.addNewQuery(
701 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
702 this.filtersModel
.getCurrentParameterState( true ),
707 this._saveSavedQueries();
711 * Remove a saved query
713 * @param {string} queryID Query id
715 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
716 this.savedQueriesModel
.removeQuery( queryID
);
718 this._saveSavedQueries();
722 * Rename a saved query
724 * @param {string} queryID Query id
725 * @param {string} newLabel New label for the query
727 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
728 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
731 queryItem
.updateLabel( newLabel
);
733 this._saveSavedQueries();
737 * Set a saved query as default
739 * @param {string} queryID Query Id. If null is given, default
742 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
743 this.savedQueriesModel
.setDefault( queryID
);
744 this._saveSavedQueries();
750 * @param {string} queryID Query id
752 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
753 var currentMatchingQuery
,
754 params
= this.savedQueriesModel
.getItemParams( queryID
);
756 currentMatchingQuery
= this.findQueryMatchingCurrentState();
759 currentMatchingQuery
&&
760 currentMatchingQuery
.getID() === queryID
762 // If the query we want to load is the one that is already
763 // loaded, don't reload it
767 if ( this.applyParamChange( params
) ) {
768 // Update changes list only if there was a difference in filter selection
769 this.updateChangesList();
771 this.uriProcessor
.updateURL( params
);
774 // Log filter grouping
775 this.trackFilterGroupings( 'savedfilters' );
779 * Check whether the current filter and highlight state exists
780 * in the saved queries model.
782 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
784 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
785 return this.savedQueriesModel
.findMatchingQuery(
786 this.filtersModel
.getCurrentParameterState( true )
791 * Save the current state of the saved queries model with all
792 * query item representation in the user settings.
794 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
795 var stringified
, oldPrefValue
,
796 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
797 state
= this.savedQueriesModel
.getState();
800 stringified
= JSON
.stringify( state
);
802 if ( $.byteLength( stringified
) > 65535 ) {
803 // Sanity check, since the preference can only hold that.
807 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
808 // The queries were converted from the previous version
809 // Keep the old string in the [prefname]-versionbackup
810 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
812 // Save the old preference in the backup preference
813 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
814 // Update the preference for this session
815 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
818 // Save the preference
819 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
820 // Update the preference for this session
821 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
823 // Tag as already saved so we don't do this again
824 this.wereSavedQueriesSaved
= true;
828 * Update sticky preferences with current model state
830 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
831 // Update default sticky values with selected, whether they came from
832 // the initial defaults or from the URL value that is being normalized
833 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
834 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
836 // TODO: Make these automatic by having the model go over sticky
837 // items and update their default values automatically
841 * Update the limit default value
843 * @param {number} newValue New value
845 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
846 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
850 * Update the days default value
852 * @param {number} newValue New value
854 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
855 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
859 * Update the group by page default value
861 * @param {boolean} newValue New value
863 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
864 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
868 * Update a numeric preference with a new value
870 * @param {string} prefName Preference name
871 * @param {number|string} newValue New value
873 mw
.rcfilters
.Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
874 if ( !$.isNumeric( newValue
) ) {
878 newValue
= Number( newValue
);
880 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
881 // Save the preference
882 new mw
.Api().saveOption( prefName
, newValue
);
883 // Update the preference for this session
884 mw
.user
.options
.set( prefName
, newValue
);
889 * Synchronize the URL with the current state of the filters
890 * without adding an history entry.
892 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
893 this.uriProcessor
.updateURL();
897 * Update filter state (selection and highlighting) based
898 * on current URL values.
900 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
901 * list based on the updated model.
903 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
904 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
906 this.uriProcessor
.updateModelBasedOnQuery();
908 // Update the sticky preferences, in case we received a value
910 this.updateStickyPreferences();
912 // Only update and fetch new results if it is requested
913 if ( fetchChangesList
) {
914 this.updateChangesList();
919 * Update the list of changes and notify the model
921 * @param {Object} [params] Extra parameters to add to the API call
922 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
923 * @return {jQuery.Promise} Promise that is resolved when the update is complete
925 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
926 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
928 if ( updateMode
=== this.FILTER_CHANGE
) {
929 this.uriProcessor
.updateURL( params
);
931 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
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(
945 pieces
.noResultsDetails
,
947 // separator between old and new changes
948 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
951 // Do nothing for failure
953 .always( function () {
954 this.updatingChangesList
= false;
959 * Get an object representing the default parameter state, whether
960 * it is from the model defaults or from the saved queries.
962 * @return {Object} Default parameters
964 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
965 if ( this.savedQueriesModel
.getDefault() ) {
966 return this.savedQueriesModel
.getDefaultParams();
968 return this.filtersModel
.getDefaultParams();
973 * Query the list of changes from the server for the current filters
975 * @param {string} counterId Id for this request. To allow concurrent requests
976 * not to invalidate each other.
977 * @param {Object} [params={}] Parameters to add to the query
979 * @return {jQuery.Promise} Promise object resolved with { content, status }
981 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
982 var uri
= this.uriProcessor
.getUpdatedUri(),
983 stickyParams
= this.filtersModel
.getStickyParamsValues(),
987 params
= params
|| {};
988 params
.action
= 'render'; // bypasses MW chrome
990 uri
.extend( params
);
992 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
993 requestId
= ++this.requestCounter
[ counterId
];
994 latestRequest = function () {
995 return requestId
=== this.requestCounter
[ counterId
];
998 // Sticky parameters override the URL params
999 // this is to make sure that whether we represent
1000 // the sticky params in the URL or not (they may
1001 // be normalized out) the sticky parameters are
1002 // always being sent to the server with their
1003 // current/default values
1004 uri
.extend( stickyParams
);
1006 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1008 function ( content
, message
, jqXHR
) {
1009 if ( !latestRequest() ) {
1010 return $.Deferred().reject();
1014 status
: jqXHR
.status
1017 // RC returns 404 when there is no results
1018 function ( jqXHR
) {
1019 if ( latestRequest() ) {
1020 return $.Deferred().resolve(
1022 content
: jqXHR
.responseText
,
1023 status
: jqXHR
.status
1032 * Fetch the list of changes from the server for the current filters
1034 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1037 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1038 return this._queryChangesList( 'updateChangesList' )
1043 // Status code 0 is not HTTP status code,
1044 // but is valid value of XMLHttpRequest status.
1045 // It is used for variety of network errors, for example
1046 // when an AJAX call was cancelled before getting the response
1047 if ( data
&& data
.status
=== 0 ) {
1049 changes
: 'NO_RESULTS',
1050 // We need empty result set, to avoid exceptions because of undefined value
1052 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1056 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1057 data
? data
.content
: ''
1060 return this._extractChangesListInfo( $parsed
, data
.status
);
1066 * Track usage of highlight feature
1068 * @param {string} action
1069 * @param {Array|Object|string} filters
1071 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1072 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1073 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1075 'event.ChangesListHighlights',
1079 userId
: mw
.user
.getId()
1085 * Track filter grouping usage
1087 * @param {string} action Action taken
1089 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1090 var controller
= this,
1091 rightNow
= new Date().getTime(),
1092 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1093 // Get all current filters
1094 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1095 return item
.getName();
1098 action
= action
|| 'filtermenu';
1100 // Check if these filters were the ones we just logged previously
1101 // (Don't log the same grouping twice, in case the user opens/closes)
1102 // the menu without action, or with the same result
1104 // Only log if the two arrays are different in size
1105 filters
.length
!== this.prevLoggedItems
.length
||
1106 // Or if any filters are not the same as the cached filters
1107 filters
.some( function ( filterName
) {
1108 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1110 // Or if any cached filters are not the same as given filters
1111 this.prevLoggedItems
.some( function ( filterName
) {
1112 return filters
.indexOf( filterName
) === -1;
1115 filters
.forEach( function ( filterName
) {
1117 'event.ChangesListFilterGrouping',
1120 groupIdentifier
: randomIdentifier
,
1122 userId
: mw
.user
.getId()
1127 // Cache the filter names
1128 this.prevLoggedItems
= filters
;
1133 * Apply a change of parameters to the model state, and check whether
1134 * the new state is different than the old state.
1136 * @param {Object} newParamState New parameter state to apply
1137 * @return {boolean} New applied model state is different than the previous state
1139 mw
.rcfilters
.Controller
.prototype.applyParamChange = function ( newParamState
) {
1141 before
= this.filtersModel
.getSelectedState();
1143 this.filtersModel
.updateStateFromParams( newParamState
);
1145 after
= this.filtersModel
.getSelectedState();
1147 return !OO
.compare( before
, after
);
1151 * Mark all changes as seen on Watchlist
1153 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1154 var api
= new mw
.Api();
1155 api
.postWithToken( 'csrf', {
1157 action
: 'setnotificationtimestamp',
1158 entirewatchlist
: true
1159 } ).then( function () {
1160 this.updateChangesList( null, 'markSeen' );
1165 * Set the current search for the system.
1167 * @param {string} searchQuery Search query, including triggers
1169 mw
.rcfilters
.Controller
.prototype.setSearch = function ( searchQuery
) {
1170 this.filtersModel
.setSearch( searchQuery
);
1174 * Switch the view by changing the search query trigger
1175 * without changing the search term
1177 * @param {string} view View to change to
1179 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
1181 this.filtersModel
.getViewTrigger( view
) +
1182 this.filtersModel
.removeViewTriggers( this.filtersModel
.getSearch() )
1187 * Reset the search for a specific view. This means we null the search query
1188 * and replace it with the relevant trigger for the requested view
1190 * @param {string} [view='default'] View to change to
1192 mw
.rcfilters
.Controller
.prototype.resetSearchForView = function ( view
) {
1193 view
= view
|| 'default';
1196 this.filtersModel
.getViewTrigger( view
)
1199 }( mediaWiki
, jQuery
) );