1 /* eslint-disable no-restricted-properties */
4 var byteLength
= require( 'mediawiki.String' ).byteLength
;
6 /* eslint no-underscore-dangle: "off" */
8 * Controller for the filters in Recent Changes
12 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
13 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
14 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
15 * @param {Object} config Additional configuration
16 * @cfg {string} savedQueriesPreferenceName Where to save the saved queries
17 * @cfg {string} daysPreferenceName Preference name for the days filter
18 * @cfg {string} limitPreferenceName Preference name for the limit filter
19 * @cfg {string} collapsedPreferenceName Preference name for collapsing and showing
20 * the active filters area
21 * @cfg {boolean} [normalizeTarget] Dictates whether or not to go through the
22 * title normalization to separate title subpage/parts into the target= url
25 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
, config
) {
26 this.filtersModel
= filtersModel
;
27 this.changesListModel
= changesListModel
;
28 this.savedQueriesModel
= savedQueriesModel
;
29 this.savedQueriesPreferenceName
= config
.savedQueriesPreferenceName
;
30 this.daysPreferenceName
= config
.daysPreferenceName
;
31 this.limitPreferenceName
= config
.limitPreferenceName
;
32 this.collapsedPreferenceName
= config
.collapsedPreferenceName
;
33 this.normalizeTarget
= !!config
.normalizeTarget
;
35 this.requestCounter
= {};
36 this.baseFilterState
= {};
37 this.uriProcessor
= null;
38 this.initialized
= false;
39 this.wereSavedQueriesSaved
= false;
41 this.prevLoggedItems
= [];
43 this.FILTER_CHANGE
= 'filterChange';
44 this.SHOW_NEW_CHANGES
= 'showNewChanges';
45 this.LIVE_UPDATE
= 'liveUpdate';
49 OO
.initClass( mw
.rcfilters
.Controller
);
52 * Initialize the filter and parameter states
54 * @param {Array} filterStructure Filter definition and structure for the model
55 * @param {Object} [namespaceStructure] Namespace definition
56 * @param {Object} [tagList] Tag definition
57 * @param {Object} [conditionalViews] Conditional view definition
59 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
, conditionalViews
) {
60 var parsedSavedQueries
, pieces
,
61 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
62 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
64 views
= $.extend( true, {}, conditionalViews
),
69 if ( namespaceStructure
) {
71 $.each( namespaceStructure
, function ( namespaceID
, label
) {
72 // Build and clean up the individual namespace items definition
75 label
: label
|| mw
.msg( 'blanknamespace' ),
78 mw
.Title
.isTalkNamespace( namespaceID
) ?
81 cssClass
: 'mw-changeslist-ns-' + namespaceID
86 title
: mw
.msg( 'namespaces' ),
89 // Group definition (single group)
90 name
: 'namespace', // parameter name is singular
91 type
: 'string_options',
92 title
: mw
.msg( 'namespaces' ),
93 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
114 title
: mw
.msg( 'rcfilters-view-tags' ),
117 // Group definition (single group)
118 name
: 'tagfilter', // Parameter name
119 type
: 'string_options',
120 title
: 'rcfilters-view-tags', // Message key
121 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
129 // Add parameter range operations
134 type
: 'single_option',
135 title
: '', // Because it's a hidden group, this title actually appears nowhere
137 allowArbitrary
: true,
138 validate
: $.isNumeric
,
140 min
: 0, // The server normalizes negative numbers to 0 results
143 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
144 'default': mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
146 filters
: displayConfig
.limitArray
.map( function ( num
) {
147 return controller
._createFilterDataFromNumber( num
, num
);
152 type
: 'single_option',
153 title
: '', // Because it's a hidden group, this title actually appears nowhere
155 allowArbitrary
: true,
156 validate
: $.isNumeric
,
159 max
: displayConfig
.maxDays
161 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
162 numToLabelFunc: function ( i
) {
163 return Number( i
) < 1 ?
164 ( Number( i
) * 24 ).toFixed( 2 ) :
167 'default': mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
170 // Hours (1, 2, 6, 12)
171 0.04166, 0.0833, 0.25, 0.5
173 ].concat( displayConfig
.daysArray
)
174 .map( function ( num
) {
175 return controller
._createFilterDataFromNumber(
177 // Convert fractions of days to number of hours for the labels
178 num
< 1 ? Math
.round( num
* 24 ) : num
190 title
: '', // Because it's a hidden group, this title actually appears nowhere
196 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
203 // Before we do anything, we need to see if we require additional items in the
204 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
205 // groups; if we ever expand it, this might need further generalization:
206 $.each( views
, function ( viewName
, viewData
) {
207 viewData
.groups
.forEach( function ( groupData
) {
208 var extraValues
= [];
209 if ( groupData
.allowArbitrary
) {
210 // If the value in the URI isn't in the group, add it
211 if ( uri
.query
[ groupData
.name
] !== undefined ) {
212 extraValues
.push( uri
.query
[ groupData
.name
] );
214 // If the default value isn't in the group, add it
215 if ( groupData
.default !== undefined ) {
216 extraValues
.push( String( groupData
.default ) );
218 controller
.addNumberValuesToGroup( groupData
, extraValues
);
223 // Initialize the model
224 this.filtersModel
.initializeFilters( filterStructure
, views
);
226 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
228 { normalizeTarget
: this.normalizeTarget
}
231 if ( !mw
.user
.isAnon() ) {
233 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
235 parsedSavedQueries
= {};
238 // Initialize saved queries
239 this.savedQueriesModel
.initialize( parsedSavedQueries
);
240 if ( this.savedQueriesModel
.isConverted() ) {
241 // Since we know we converted, we're going to re-save
242 // the queries so they are now migrated to the new format
243 this._saveSavedQueries();
247 if ( defaultSavedQueryExists
) {
248 // This came from the server, meaning that we have a default
249 // saved query, but the server could not load it, probably because
250 // it was pre-conversion to the new format.
251 // We need to load this query again
252 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
254 // There are either recognized parameters in the URL
255 // or there are none, but there is also no default
256 // saved query (so defaults are from the backend)
257 // We want to update the state but not fetch results
259 this.updateStateFromUrl( false );
261 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
263 // Update the changes list with the existing data
264 // so it gets processed
265 this.changesListModel
.update(
268 pieces
.noResultsDetails
,
269 true // We're using existing DOM elements
273 this.initialized
= true;
274 this.switchView( 'default' );
276 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
277 if ( this.pollingRate
) {
278 this._scheduleLiveUpdate();
283 * Check if the controller has finished initializing.
284 * @return {boolean} Controller is initialized
286 mw
.rcfilters
.Controller
.prototype.isInitialized = function () {
287 return this.initialized
;
291 * Extracts information from the changes list DOM
293 * @param {jQuery} $root Root DOM to find children from
294 * @param {boolean} [statusCode] Server response status code
295 * @return {Object} Information about changes list
296 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
297 * (either normally or as an error)
298 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
299 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
300 * @return {jQuery} return.fieldset Fieldset
302 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
, statusCode
) {
304 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
305 areResults
= !!$changesListContents
.length
,
306 checkForLogout
= !areResults
&& statusCode
=== 200;
308 // We check if user logged out on different tab/browser or the session has expired.
309 // 205 status code returned from the server, which indicates that we need to reload the page
310 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
311 // status code (if everything else goes well).
313 if ( checkForLogout
&& !!$root
.find( '#wpName1' ).length
) {
314 location
.reload( false );
319 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
320 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
324 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
325 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
326 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
327 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
328 } else if ( $root
.find( '.mw-changeslist-invalidtargetpage' ).length
) {
329 info
.noResultsDetails
= 'NO_RESULTS_INVALID_TARGET_PAGE';
331 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
339 * Create filter data from a number, for the filters that are numerical value
341 * @param {number} num Number
342 * @param {number} numForDisplay Number for the label
343 * @return {Object} Filter data
345 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
348 label
: mw
.language
.convertNumber( numForDisplay
)
353 * Add an arbitrary values to groups that allow arbitrary values
355 * @param {Object} groupData Group data
356 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
358 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
359 var controller
= this,
360 normalizeWithinRange = function ( range
, val
) {
361 if ( val
< range
.min
) {
362 return range
.min
; // Min
363 } else if ( val
>= range
.max
) {
364 return range
.max
; // Max
369 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
371 // Normalize the arbitrary values and the default value for a range
372 if ( groupData
.range
) {
373 arbitraryValues
= arbitraryValues
.map( function ( val
) {
374 return normalizeWithinRange( groupData
.range
, val
);
377 // Normalize the default, since that's user defined
378 if ( groupData
.default !== undefined ) {
379 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
383 // This is only true for single_option group
384 // We assume these are the only groups that will allow for
385 // arbitrary, since it doesn't make any sense for the other
387 arbitraryValues
.forEach( function ( val
) {
389 // If the group allows for arbitrary data
390 groupData
.allowArbitrary
&&
391 // and it is single_option (or string_options, but we
392 // don't have cases of those yet, nor do we plan to)
393 groupData
.type
=== 'single_option' &&
394 // and, if there is a validate method and it passes on
396 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
397 // but if that value isn't already in the definition
399 .map( function ( filterData
) {
400 return String( filterData
.name
);
402 .indexOf( String( val
) ) === -1
404 // Add the filter information
405 groupData
.filters
.push( controller
._createFilterDataFromNumber(
407 groupData
.numToLabelFunc
?
408 groupData
.numToLabelFunc( val
) :
412 // If there's a sort function set up, re-sort the values
413 if ( groupData
.sortFunc
) {
414 groupData
.filters
.sort( groupData
.sortFunc
);
421 * Reset to default filters
423 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
424 var params
= this._getDefaultParams();
425 if ( this.applyParamChange( params
) ) {
426 // Only update the changes list if there was a change to actual filters
427 this.updateChangesList();
429 this.uriProcessor
.updateURL( params
);
434 * Check whether the default values of the filters are all false.
436 * @return {boolean} Defaults are all false
438 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
439 return $.isEmptyObject( this._getDefaultParams() );
443 * Empty all selected filters
445 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
446 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
447 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
449 if ( this.applyParamChange( {} ) ) {
450 // Only update the changes list if there was a change to actual filters
451 this.updateChangesList();
453 this.uriProcessor
.updateURL();
456 if ( highlightedFilterNames
) {
457 this._trackHighlight( 'clearAll', highlightedFilterNames
);
462 * Update the selected state of a filter
464 * @param {string} filterName Filter name
465 * @param {boolean} [isSelected] Filter selected state
467 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
468 var filterItem
= this.filtersModel
.getItemByName( filterName
);
471 // If no filter was found, break
475 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
477 if ( filterItem
.isSelected() !== isSelected
) {
478 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
480 this.updateChangesList();
482 // Check filter interactions
483 this.filtersModel
.reassessFilterInteractions( filterItem
);
488 * Clear both highlight and selection of a filter
490 * @param {string} filterName Name of the filter item
492 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
493 var filterItem
= this.filtersModel
.getItemByName( filterName
),
494 isHighlighted
= filterItem
.isHighlighted(),
495 isSelected
= filterItem
.isSelected();
497 if ( isSelected
|| isHighlighted
) {
498 this.filtersModel
.clearHighlightColor( filterName
);
499 this.filtersModel
.toggleFilterSelected( filterName
, false );
502 // Only update the changes list if the filter changed
503 // its selection state. If it only changed its highlight
505 this.updateChangesList();
508 this.filtersModel
.reassessFilterInteractions( filterItem
);
510 // Log filter grouping
511 this.trackFilterGroupings( 'removefilter' );
514 if ( isHighlighted
) {
515 this._trackHighlight( 'clear', filterName
);
520 * Toggle the highlight feature on and off
522 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
523 this.filtersModel
.toggleHighlight();
524 this.uriProcessor
.updateURL();
526 if ( this.filtersModel
.isHighlightEnabled() ) {
527 mw
.hook( 'RcFilters.highlight.enable' ).fire();
532 * Toggle the namespaces inverted feature on and off
534 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
535 this.filtersModel
.toggleInvertedNamespaces();
537 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
538 function ( filterItem
) { return filterItem
.isSelected(); }
541 // Only re-fetch results if there are namespace items that are actually selected
542 this.updateChangesList();
544 this.uriProcessor
.updateURL();
549 * Set the value of the 'showlinkedto' parameter
550 * @param {boolean} value
552 mw
.rcfilters
.Controller
.prototype.setShowLinkedTo = function ( value
) {
553 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
554 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
556 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
557 this.uriProcessor
.updateURL();
558 // reload the results only when target is set
559 if ( targetItem
.getValue() ) {
560 this.updateChangesList();
565 * Set the target page
566 * @param {string} page
568 mw
.rcfilters
.Controller
.prototype.setTargetPage = function ( page
) {
569 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
570 targetItem
.setValue( page
);
571 this.uriProcessor
.updateURL();
572 this.updateChangesList();
576 * Set the highlight color for a filter item
578 * @param {string} filterName Name of the filter item
579 * @param {string} color Selected color
581 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
582 this.filtersModel
.setHighlightColor( filterName
, color
);
583 this.uriProcessor
.updateURL();
584 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
588 * Clear highlight for a filter item
590 * @param {string} filterName Name of the filter item
592 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
593 this.filtersModel
.clearHighlightColor( filterName
);
594 this.uriProcessor
.updateURL();
595 this._trackHighlight( 'clear', filterName
);
599 * Enable or disable live updates.
600 * @param {boolean} enable True to enable, false to disable
602 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
603 this.changesListModel
.toggleLiveUpdate( enable
);
604 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
605 this.updateChangesList( null, this.LIVE_UPDATE
);
610 * Set a timeout for the next live update.
613 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
614 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
618 * Perform a live update.
621 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
622 if ( !this._shouldCheckForNewChanges() ) {
623 // skip this turn and check back later
624 this._scheduleLiveUpdate();
628 this._checkForNewChanges()
629 .then( function ( statusCode
) {
630 // no result is 204 with the 'peek' param
632 var newChanges
= statusCode
=== 200;
634 if ( !this._shouldCheckForNewChanges() ) {
635 // by the time the response is received,
636 // it may not be appropriate anymore
640 // 205 is the status code returned from server when user's logged in/out
641 // status is not matching while fetching live update changes.
642 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
644 if ( statusCode
=== 205 ) {
645 location
.reload( false );
650 if ( this.changesListModel
.getLiveUpdate() ) {
651 return this.updateChangesList( null, this.LIVE_UPDATE
);
653 this.changesListModel
.setNewChangesExist( true );
657 .always( this._scheduleLiveUpdate
.bind( this ) );
661 * @return {boolean} It's appropriate to check for new changes now
664 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
665 return !document
.hidden
&&
666 !this.filtersModel
.hasConflict() &&
667 !this.changesListModel
.getNewChangesExist() &&
668 !this.updatingChangesList
&&
669 this.changesListModel
.getNextFrom();
673 * Check if new changes, newer than those currently shown, are available
675 * @return {jQuery.Promise} Promise object that resolves with a bool
676 * specifying if there are new changes or not
680 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
683 peek
: 1, // bypasses ChangesList specific UI
684 from: this.changesListModel
.getNextFrom(),
685 isAnon
: mw
.user
.isAnon()
687 return this._queryChangesList( 'liveUpdate', params
).then(
695 * Show the new changes
697 * @return {jQuery.Promise} Promise object that resolves after
698 * fetching and showing the new changes
700 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
701 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
705 * Save the current model state as a saved query
707 * @param {string} [label] Label of the saved query
708 * @param {boolean} [setAsDefault=false] This query should be set as the default
710 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
712 this.savedQueriesModel
.addNewQuery(
713 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
714 this.filtersModel
.getCurrentParameterState( true ),
719 this._saveSavedQueries();
723 * Remove a saved query
725 * @param {string} queryID Query id
727 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
728 this.savedQueriesModel
.removeQuery( queryID
);
730 this._saveSavedQueries();
734 * Rename a saved query
736 * @param {string} queryID Query id
737 * @param {string} newLabel New label for the query
739 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
740 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
743 queryItem
.updateLabel( newLabel
);
745 this._saveSavedQueries();
749 * Set a saved query as default
751 * @param {string} queryID Query Id. If null is given, default
754 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
755 this.savedQueriesModel
.setDefault( queryID
);
756 this._saveSavedQueries();
762 * @param {string} queryID Query id
764 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
765 var currentMatchingQuery
,
766 params
= this.savedQueriesModel
.getItemParams( queryID
);
768 currentMatchingQuery
= this.findQueryMatchingCurrentState();
771 currentMatchingQuery
&&
772 currentMatchingQuery
.getID() === queryID
774 // If the query we want to load is the one that is already
775 // loaded, don't reload it
779 if ( this.applyParamChange( params
) ) {
780 // Update changes list only if there was a difference in filter selection
781 this.updateChangesList();
783 this.uriProcessor
.updateURL( params
);
786 // Log filter grouping
787 this.trackFilterGroupings( 'savedfilters' );
791 * Check whether the current filter and highlight state exists
792 * in the saved queries model.
794 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
796 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
797 return this.savedQueriesModel
.findMatchingQuery(
798 this.filtersModel
.getCurrentParameterState( true )
803 * Save the current state of the saved queries model with all
804 * query item representation in the user settings.
806 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
807 var stringified
, oldPrefValue
,
808 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
809 state
= this.savedQueriesModel
.getState();
812 stringified
= JSON
.stringify( state
);
814 if ( byteLength( stringified
) > 65535 ) {
815 // Sanity check, since the preference can only hold that.
819 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
820 // The queries were converted from the previous version
821 // Keep the old string in the [prefname]-versionbackup
822 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
824 // Save the old preference in the backup preference
825 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
826 // Update the preference for this session
827 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
830 // Save the preference
831 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
832 // Update the preference for this session
833 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
835 // Tag as already saved so we don't do this again
836 this.wereSavedQueriesSaved
= true;
840 * Update sticky preferences with current model state
842 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
843 // Update default sticky values with selected, whether they came from
844 // the initial defaults or from the URL value that is being normalized
845 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).findSelectedItems()[ 0 ].getParamName() );
846 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).findSelectedItems()[ 0 ].getParamName() );
848 // TODO: Make these automatic by having the model go over sticky
849 // items and update their default values automatically
853 * Update the limit default value
855 * @param {number} newValue New value
857 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
858 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
862 * Update the days default value
864 * @param {number} newValue New value
866 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
867 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
871 * Update the group by page default value
873 * @param {boolean} newValue New value
875 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
876 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
880 * Update the collapsed state value
882 * @param {boolean} isCollapsed Filter area is collapsed
884 mw
.rcfilters
.Controller
.prototype.updateCollapsedState = function ( isCollapsed
) {
885 this.updateNumericPreference( this.collapsedPreferenceName
, Number( isCollapsed
) );
889 * Update a numeric preference with a new value
891 * @param {string} prefName Preference name
892 * @param {number|string} newValue New value
894 mw
.rcfilters
.Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
895 if ( !$.isNumeric( newValue
) ) {
899 newValue
= Number( newValue
);
901 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
902 // Save the preference
903 new mw
.Api().saveOption( prefName
, newValue
);
904 // Update the preference for this session
905 mw
.user
.options
.set( prefName
, newValue
);
910 * Synchronize the URL with the current state of the filters
911 * without adding an history entry.
913 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
914 this.uriProcessor
.updateURL();
918 * Update filter state (selection and highlighting) based
919 * on current URL values.
921 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
922 * list based on the updated model.
924 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
925 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
927 this.uriProcessor
.updateModelBasedOnQuery();
929 // Update the sticky preferences, in case we received a value
931 this.updateStickyPreferences();
933 // Only update and fetch new results if it is requested
934 if ( fetchChangesList
) {
935 this.updateChangesList();
940 * Update the list of changes and notify the model
942 * @param {Object} [params] Extra parameters to add to the API call
943 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
944 * @return {jQuery.Promise} Promise that is resolved when the update is complete
946 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
947 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
949 if ( updateMode
=== this.FILTER_CHANGE
) {
950 this.uriProcessor
.updateURL( params
);
952 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
953 this.changesListModel
.invalidate();
955 this.changesListModel
.setNewChangesExist( false );
956 this.updatingChangesList
= true;
957 return this._fetchChangesList()
960 function ( pieces
) {
961 var $changesListContent
= pieces
.changes
,
962 $fieldset
= pieces
.fieldset
;
963 this.changesListModel
.update(
966 pieces
.noResultsDetails
,
968 // separator between old and new changes
969 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
972 // Do nothing for failure
974 .always( function () {
975 this.updatingChangesList
= false;
980 * Get an object representing the default parameter state, whether
981 * it is from the model defaults or from the saved queries.
983 * @return {Object} Default parameters
985 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
986 if ( this.savedQueriesModel
.getDefault() ) {
987 return this.savedQueriesModel
.getDefaultParams();
989 return this.filtersModel
.getDefaultParams();
994 * Query the list of changes from the server for the current filters
996 * @param {string} counterId Id for this request. To allow concurrent requests
997 * not to invalidate each other.
998 * @param {Object} [params={}] Parameters to add to the query
1000 * @return {jQuery.Promise} Promise object resolved with { content, status }
1002 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1003 var uri
= this.uriProcessor
.getUpdatedUri(),
1004 stickyParams
= this.filtersModel
.getStickyParamsValues(),
1008 params
= params
|| {};
1009 params
.action
= 'render'; // bypasses MW chrome
1011 uri
.extend( params
);
1013 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1014 requestId
= ++this.requestCounter
[ counterId
];
1015 latestRequest = function () {
1016 return requestId
=== this.requestCounter
[ counterId
];
1019 // Sticky parameters override the URL params
1020 // this is to make sure that whether we represent
1021 // the sticky params in the URL or not (they may
1022 // be normalized out) the sticky parameters are
1023 // always being sent to the server with their
1024 // current/default values
1025 uri
.extend( stickyParams
);
1027 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1029 function ( content
, message
, jqXHR
) {
1030 if ( !latestRequest() ) {
1031 return $.Deferred().reject();
1035 status
: jqXHR
.status
1038 // RC returns 404 when there is no results
1039 function ( jqXHR
) {
1040 if ( latestRequest() ) {
1041 return $.Deferred().resolve(
1043 content
: jqXHR
.responseText
,
1044 status
: jqXHR
.status
1053 * Fetch the list of changes from the server for the current filters
1055 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1058 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1059 return this._queryChangesList( 'updateChangesList' )
1064 // Status code 0 is not HTTP status code,
1065 // but is valid value of XMLHttpRequest status.
1066 // It is used for variety of network errors, for example
1067 // when an AJAX call was cancelled before getting the response
1068 if ( data
&& data
.status
=== 0 ) {
1070 changes
: 'NO_RESULTS',
1071 // We need empty result set, to avoid exceptions because of undefined value
1073 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1077 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1078 data
? data
.content
: ''
1081 return this._extractChangesListInfo( $parsed
, data
.status
);
1087 * Track usage of highlight feature
1089 * @param {string} action
1090 * @param {Array|Object|string} filters
1092 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1093 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1094 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1096 'event.ChangesListHighlights',
1100 userId
: mw
.user
.getId()
1106 * Track filter grouping usage
1108 * @param {string} action Action taken
1110 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1111 var controller
= this,
1112 rightNow
= new Date().getTime(),
1113 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1114 // Get all current filters
1115 filters
= this.filtersModel
.findSelectedItems().map( function ( item
) {
1116 return item
.getName();
1119 action
= action
|| 'filtermenu';
1121 // Check if these filters were the ones we just logged previously
1122 // (Don't log the same grouping twice, in case the user opens/closes)
1123 // the menu without action, or with the same result
1125 // Only log if the two arrays are different in size
1126 filters
.length
!== this.prevLoggedItems
.length
||
1127 // Or if any filters are not the same as the cached filters
1128 filters
.some( function ( filterName
) {
1129 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1131 // Or if any cached filters are not the same as given filters
1132 this.prevLoggedItems
.some( function ( filterName
) {
1133 return filters
.indexOf( filterName
) === -1;
1136 filters
.forEach( function ( filterName
) {
1138 'event.ChangesListFilterGrouping',
1141 groupIdentifier
: randomIdentifier
,
1143 userId
: mw
.user
.getId()
1148 // Cache the filter names
1149 this.prevLoggedItems
= filters
;
1154 * Apply a change of parameters to the model state, and check whether
1155 * the new state is different than the old state.
1157 * @param {Object} newParamState New parameter state to apply
1158 * @return {boolean} New applied model state is different than the previous state
1160 mw
.rcfilters
.Controller
.prototype.applyParamChange = function ( newParamState
) {
1162 before
= this.filtersModel
.getSelectedState();
1164 this.filtersModel
.updateStateFromParams( newParamState
);
1166 after
= this.filtersModel
.getSelectedState();
1168 return !OO
.compare( before
, after
);
1172 * Mark all changes as seen on Watchlist
1174 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1175 var api
= new mw
.Api();
1176 api
.postWithToken( 'csrf', {
1178 action
: 'setnotificationtimestamp',
1179 entirewatchlist
: true
1180 } ).then( function () {
1181 this.updateChangesList( null, 'markSeen' );
1186 * Set the current search for the system.
1188 * @param {string} searchQuery Search query, including triggers
1190 mw
.rcfilters
.Controller
.prototype.setSearch = function ( searchQuery
) {
1191 this.filtersModel
.setSearch( searchQuery
);
1195 * Switch the view by changing the search query trigger
1196 * without changing the search term
1198 * @param {string} view View to change to
1200 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
1202 this.filtersModel
.getViewTrigger( view
) +
1203 this.filtersModel
.removeViewTriggers( this.filtersModel
.getSearch() )
1208 * Reset the search for a specific view. This means we null the search query
1209 * and replace it with the relevant trigger for the requested view
1211 * @param {string} [view='default'] View to change to
1213 mw
.rcfilters
.Controller
.prototype.resetSearchForView = function ( view
) {
1214 view
= view
|| 'default';
1217 this.filtersModel
.getViewTrigger( view
)