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 // eslint-disable-next-line jquery/no-each-util
72 $.each( namespaceStructure
, function ( namespaceID
, label
) {
73 // Build and clean up the individual namespace items definition
76 label
: label
|| mw
.msg( 'blanknamespace' ),
79 mw
.Title
.isTalkNamespace( namespaceID
) ?
82 cssClass
: 'mw-changeslist-ns-' + namespaceID
87 title
: mw
.msg( 'namespaces' ),
90 // Group definition (single group)
91 name
: 'namespace', // parameter name is singular
92 type
: 'string_options',
93 title
: mw
.msg( 'namespaces' ),
94 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
115 title
: mw
.msg( 'rcfilters-view-tags' ),
118 // Group definition (single group)
119 name
: 'tagfilter', // Parameter name
120 type
: 'string_options',
121 title
: 'rcfilters-view-tags', // Message key
122 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
130 // Add parameter range operations
135 type
: 'single_option',
136 title
: '', // Because it's a hidden group, this title actually appears nowhere
138 allowArbitrary
: true,
139 validate
: $.isNumeric
,
141 min
: 0, // The server normalizes negative numbers to 0 results
144 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
145 'default': mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
147 filters
: displayConfig
.limitArray
.map( function ( num
) {
148 return controller
._createFilterDataFromNumber( num
, num
);
153 type
: 'single_option',
154 title
: '', // Because it's a hidden group, this title actually appears nowhere
156 allowArbitrary
: true,
157 validate
: $.isNumeric
,
160 max
: displayConfig
.maxDays
162 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
163 numToLabelFunc: function ( i
) {
164 return Number( i
) < 1 ?
165 ( Number( i
) * 24 ).toFixed( 2 ) :
168 'default': mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
171 // Hours (1, 2, 6, 12)
172 0.04166, 0.0833, 0.25, 0.5
174 ].concat( displayConfig
.daysArray
)
175 .map( function ( num
) {
176 return controller
._createFilterDataFromNumber(
178 // Convert fractions of days to number of hours for the labels
179 num
< 1 ? Math
.round( num
* 24 ) : num
191 title
: '', // Because it's a hidden group, this title actually appears nowhere
197 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
204 // Before we do anything, we need to see if we require additional items in the
205 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
206 // groups; if we ever expand it, this might need further generalization:
207 // eslint-disable-next-line jquery/no-each-util
208 $.each( views
, function ( viewName
, viewData
) {
209 viewData
.groups
.forEach( function ( groupData
) {
210 var extraValues
= [];
211 if ( groupData
.allowArbitrary
) {
212 // If the value in the URI isn't in the group, add it
213 if ( uri
.query
[ groupData
.name
] !== undefined ) {
214 extraValues
.push( uri
.query
[ groupData
.name
] );
216 // If the default value isn't in the group, add it
217 if ( groupData
.default !== undefined ) {
218 extraValues
.push( String( groupData
.default ) );
220 controller
.addNumberValuesToGroup( groupData
, extraValues
);
225 // Initialize the model
226 this.filtersModel
.initializeFilters( filterStructure
, views
);
228 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
230 { normalizeTarget
: this.normalizeTarget
}
233 if ( !mw
.user
.isAnon() ) {
235 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
237 parsedSavedQueries
= {};
240 // Initialize saved queries
241 this.savedQueriesModel
.initialize( parsedSavedQueries
);
242 if ( this.savedQueriesModel
.isConverted() ) {
243 // Since we know we converted, we're going to re-save
244 // the queries so they are now migrated to the new format
245 this._saveSavedQueries();
249 if ( defaultSavedQueryExists
) {
250 // This came from the server, meaning that we have a default
251 // saved query, but the server could not load it, probably because
252 // it was pre-conversion to the new format.
253 // We need to load this query again
254 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
256 // There are either recognized parameters in the URL
257 // or there are none, but there is also no default
258 // saved query (so defaults are from the backend)
259 // We want to update the state but not fetch results
261 this.updateStateFromUrl( false );
263 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
265 // Update the changes list with the existing data
266 // so it gets processed
267 this.changesListModel
.update(
270 pieces
.noResultsDetails
,
271 true // We're using existing DOM elements
275 this.initialized
= true;
276 this.switchView( 'default' );
278 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
279 if ( this.pollingRate
) {
280 this._scheduleLiveUpdate();
285 * Check if the controller has finished initializing.
286 * @return {boolean} Controller is initialized
288 mw
.rcfilters
.Controller
.prototype.isInitialized = function () {
289 return this.initialized
;
293 * Extracts information from the changes list DOM
295 * @param {jQuery} $root Root DOM to find children from
296 * @param {boolean} [statusCode] Server response status code
297 * @return {Object} Information about changes list
298 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
299 * (either normally or as an error)
300 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
301 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
302 * @return {jQuery} return.fieldset Fieldset
304 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
, statusCode
) {
306 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
307 areResults
= !!$changesListContents
.length
,
308 checkForLogout
= !areResults
&& statusCode
=== 200;
310 // We check if user logged out on different tab/browser or the session has expired.
311 // 205 status code returned from the server, which indicates that we need to reload the page
312 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
313 // status code (if everything else goes well).
315 if ( checkForLogout
&& !!$root
.find( '#wpName1' ).length
) {
316 location
.reload( false );
321 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
322 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
326 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
327 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
328 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
329 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
330 } else if ( $root
.find( '.mw-changeslist-invalidtargetpage' ).length
) {
331 info
.noResultsDetails
= 'NO_RESULTS_INVALID_TARGET_PAGE';
333 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
341 * Create filter data from a number, for the filters that are numerical value
343 * @param {number} num Number
344 * @param {number} numForDisplay Number for the label
345 * @return {Object} Filter data
347 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
350 label
: mw
.language
.convertNumber( numForDisplay
)
355 * Add an arbitrary values to groups that allow arbitrary values
357 * @param {Object} groupData Group data
358 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
360 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
361 var controller
= this,
362 normalizeWithinRange = function ( range
, val
) {
363 if ( val
< range
.min
) {
364 return range
.min
; // Min
365 } else if ( val
>= range
.max
) {
366 return range
.max
; // Max
371 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
373 // Normalize the arbitrary values and the default value for a range
374 if ( groupData
.range
) {
375 arbitraryValues
= arbitraryValues
.map( function ( val
) {
376 return normalizeWithinRange( groupData
.range
, val
);
379 // Normalize the default, since that's user defined
380 if ( groupData
.default !== undefined ) {
381 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
385 // This is only true for single_option group
386 // We assume these are the only groups that will allow for
387 // arbitrary, since it doesn't make any sense for the other
389 arbitraryValues
.forEach( function ( val
) {
391 // If the group allows for arbitrary data
392 groupData
.allowArbitrary
&&
393 // and it is single_option (or string_options, but we
394 // don't have cases of those yet, nor do we plan to)
395 groupData
.type
=== 'single_option' &&
396 // and, if there is a validate method and it passes on
398 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
399 // but if that value isn't already in the definition
401 .map( function ( filterData
) {
402 return String( filterData
.name
);
404 .indexOf( String( val
) ) === -1
406 // Add the filter information
407 groupData
.filters
.push( controller
._createFilterDataFromNumber(
409 groupData
.numToLabelFunc
?
410 groupData
.numToLabelFunc( val
) :
414 // If there's a sort function set up, re-sort the values
415 if ( groupData
.sortFunc
) {
416 groupData
.filters
.sort( groupData
.sortFunc
);
423 * Reset to default filters
425 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
426 var params
= this._getDefaultParams();
427 if ( this.applyParamChange( params
) ) {
428 // Only update the changes list if there was a change to actual filters
429 this.updateChangesList();
431 this.uriProcessor
.updateURL( params
);
436 * Check whether the default values of the filters are all false.
438 * @return {boolean} Defaults are all false
440 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
441 return $.isEmptyObject( this._getDefaultParams() );
445 * Empty all selected filters
447 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
448 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
449 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
451 if ( this.applyParamChange( {} ) ) {
452 // Only update the changes list if there was a change to actual filters
453 this.updateChangesList();
455 this.uriProcessor
.updateURL();
458 if ( highlightedFilterNames
) {
459 this._trackHighlight( 'clearAll', highlightedFilterNames
);
464 * Update the selected state of a filter
466 * @param {string} filterName Filter name
467 * @param {boolean} [isSelected] Filter selected state
469 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
470 var filterItem
= this.filtersModel
.getItemByName( filterName
);
473 // If no filter was found, break
477 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
479 if ( filterItem
.isSelected() !== isSelected
) {
480 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
482 this.updateChangesList();
484 // Check filter interactions
485 this.filtersModel
.reassessFilterInteractions( filterItem
);
490 * Clear both highlight and selection of a filter
492 * @param {string} filterName Name of the filter item
494 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
495 var filterItem
= this.filtersModel
.getItemByName( filterName
),
496 isHighlighted
= filterItem
.isHighlighted(),
497 isSelected
= filterItem
.isSelected();
499 if ( isSelected
|| isHighlighted
) {
500 this.filtersModel
.clearHighlightColor( filterName
);
501 this.filtersModel
.toggleFilterSelected( filterName
, false );
504 // Only update the changes list if the filter changed
505 // its selection state. If it only changed its highlight
507 this.updateChangesList();
510 this.filtersModel
.reassessFilterInteractions( filterItem
);
512 // Log filter grouping
513 this.trackFilterGroupings( 'removefilter' );
516 if ( isHighlighted
) {
517 this._trackHighlight( 'clear', filterName
);
522 * Toggle the highlight feature on and off
524 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
525 this.filtersModel
.toggleHighlight();
526 this.uriProcessor
.updateURL();
528 if ( this.filtersModel
.isHighlightEnabled() ) {
529 mw
.hook( 'RcFilters.highlight.enable' ).fire();
534 * Toggle the namespaces inverted feature on and off
536 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
537 this.filtersModel
.toggleInvertedNamespaces();
539 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
540 function ( filterItem
) { return filterItem
.isSelected(); }
543 // Only re-fetch results if there are namespace items that are actually selected
544 this.updateChangesList();
546 this.uriProcessor
.updateURL();
551 * Set the value of the 'showlinkedto' parameter
552 * @param {boolean} value
554 mw
.rcfilters
.Controller
.prototype.setShowLinkedTo = function ( value
) {
555 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
556 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
558 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
559 this.uriProcessor
.updateURL();
560 // reload the results only when target is set
561 if ( targetItem
.getValue() ) {
562 this.updateChangesList();
567 * Set the target page
568 * @param {string} page
570 mw
.rcfilters
.Controller
.prototype.setTargetPage = function ( page
) {
571 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
572 targetItem
.setValue( page
);
573 this.uriProcessor
.updateURL();
574 this.updateChangesList();
578 * Set the highlight color for a filter item
580 * @param {string} filterName Name of the filter item
581 * @param {string} color Selected color
583 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
584 this.filtersModel
.setHighlightColor( filterName
, color
);
585 this.uriProcessor
.updateURL();
586 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
590 * Clear highlight for a filter item
592 * @param {string} filterName Name of the filter item
594 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
595 this.filtersModel
.clearHighlightColor( filterName
);
596 this.uriProcessor
.updateURL();
597 this._trackHighlight( 'clear', filterName
);
601 * Enable or disable live updates.
602 * @param {boolean} enable True to enable, false to disable
604 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
605 this.changesListModel
.toggleLiveUpdate( enable
);
606 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
607 this.updateChangesList( null, this.LIVE_UPDATE
);
612 * Set a timeout for the next live update.
615 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
616 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
620 * Perform a live update.
623 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
624 if ( !this._shouldCheckForNewChanges() ) {
625 // skip this turn and check back later
626 this._scheduleLiveUpdate();
630 this._checkForNewChanges()
631 .then( function ( statusCode
) {
632 // no result is 204 with the 'peek' param
634 var newChanges
= statusCode
=== 200;
636 if ( !this._shouldCheckForNewChanges() ) {
637 // by the time the response is received,
638 // it may not be appropriate anymore
642 // 205 is the status code returned from server when user's logged in/out
643 // status is not matching while fetching live update changes.
644 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
646 if ( statusCode
=== 205 ) {
647 location
.reload( false );
652 if ( this.changesListModel
.getLiveUpdate() ) {
653 return this.updateChangesList( null, this.LIVE_UPDATE
);
655 this.changesListModel
.setNewChangesExist( true );
659 .always( this._scheduleLiveUpdate
.bind( this ) );
663 * @return {boolean} It's appropriate to check for new changes now
666 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
667 return !document
.hidden
&&
668 !this.filtersModel
.hasConflict() &&
669 !this.changesListModel
.getNewChangesExist() &&
670 !this.updatingChangesList
&&
671 this.changesListModel
.getNextFrom();
675 * Check if new changes, newer than those currently shown, are available
677 * @return {jQuery.Promise} Promise object that resolves with a bool
678 * specifying if there are new changes or not
682 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
685 peek
: 1, // bypasses ChangesList specific UI
686 from: this.changesListModel
.getNextFrom(),
687 isAnon
: mw
.user
.isAnon()
689 return this._queryChangesList( 'liveUpdate', params
).then(
697 * Show the new changes
699 * @return {jQuery.Promise} Promise object that resolves after
700 * fetching and showing the new changes
702 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
703 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
707 * Save the current model state as a saved query
709 * @param {string} [label] Label of the saved query
710 * @param {boolean} [setAsDefault=false] This query should be set as the default
712 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
714 this.savedQueriesModel
.addNewQuery(
715 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
716 this.filtersModel
.getCurrentParameterState( true ),
721 this._saveSavedQueries();
725 * Remove a saved query
727 * @param {string} queryID Query id
729 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
730 this.savedQueriesModel
.removeQuery( queryID
);
732 this._saveSavedQueries();
736 * Rename a saved query
738 * @param {string} queryID Query id
739 * @param {string} newLabel New label for the query
741 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
742 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
745 queryItem
.updateLabel( newLabel
);
747 this._saveSavedQueries();
751 * Set a saved query as default
753 * @param {string} queryID Query Id. If null is given, default
756 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
757 this.savedQueriesModel
.setDefault( queryID
);
758 this._saveSavedQueries();
764 * @param {string} queryID Query id
766 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
767 var currentMatchingQuery
,
768 params
= this.savedQueriesModel
.getItemParams( queryID
);
770 currentMatchingQuery
= this.findQueryMatchingCurrentState();
773 currentMatchingQuery
&&
774 currentMatchingQuery
.getID() === queryID
776 // If the query we want to load is the one that is already
777 // loaded, don't reload it
781 if ( this.applyParamChange( params
) ) {
782 // Update changes list only if there was a difference in filter selection
783 this.updateChangesList();
785 this.uriProcessor
.updateURL( params
);
788 // Log filter grouping
789 this.trackFilterGroupings( 'savedfilters' );
793 * Check whether the current filter and highlight state exists
794 * in the saved queries model.
796 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
798 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
799 return this.savedQueriesModel
.findMatchingQuery(
800 this.filtersModel
.getCurrentParameterState( true )
805 * Save the current state of the saved queries model with all
806 * query item representation in the user settings.
808 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
809 var stringified
, oldPrefValue
,
810 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
811 state
= this.savedQueriesModel
.getState();
814 stringified
= JSON
.stringify( state
);
816 if ( byteLength( stringified
) > 65535 ) {
817 // Sanity check, since the preference can only hold that.
821 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
822 // The queries were converted from the previous version
823 // Keep the old string in the [prefname]-versionbackup
824 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
826 // Save the old preference in the backup preference
827 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
828 // Update the preference for this session
829 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
832 // Save the preference
833 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
834 // Update the preference for this session
835 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
837 // Tag as already saved so we don't do this again
838 this.wereSavedQueriesSaved
= true;
842 * Update sticky preferences with current model state
844 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
845 // Update default sticky values with selected, whether they came from
846 // the initial defaults or from the URL value that is being normalized
847 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).findSelectedItems()[ 0 ].getParamName() );
848 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).findSelectedItems()[ 0 ].getParamName() );
850 // TODO: Make these automatic by having the model go over sticky
851 // items and update their default values automatically
855 * Update the limit default value
857 * @param {number} newValue New value
859 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
860 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
864 * Update the days default value
866 * @param {number} newValue New value
868 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
869 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
873 * Update the group by page default value
875 * @param {boolean} newValue New value
877 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
878 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
882 * Update the collapsed state value
884 * @param {boolean} isCollapsed Filter area is collapsed
886 mw
.rcfilters
.Controller
.prototype.updateCollapsedState = function ( isCollapsed
) {
887 this.updateNumericPreference( this.collapsedPreferenceName
, Number( isCollapsed
) );
891 * Update a numeric preference with a new value
893 * @param {string} prefName Preference name
894 * @param {number|string} newValue New value
896 mw
.rcfilters
.Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
897 if ( !$.isNumeric( newValue
) ) {
901 newValue
= Number( newValue
);
903 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
904 // Save the preference
905 new mw
.Api().saveOption( prefName
, newValue
);
906 // Update the preference for this session
907 mw
.user
.options
.set( prefName
, newValue
);
912 * Synchronize the URL with the current state of the filters
913 * without adding an history entry.
915 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
916 this.uriProcessor
.updateURL();
920 * Update filter state (selection and highlighting) based
921 * on current URL values.
923 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
924 * list based on the updated model.
926 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
927 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
929 this.uriProcessor
.updateModelBasedOnQuery();
931 // Update the sticky preferences, in case we received a value
933 this.updateStickyPreferences();
935 // Only update and fetch new results if it is requested
936 if ( fetchChangesList
) {
937 this.updateChangesList();
942 * Update the list of changes and notify the model
944 * @param {Object} [params] Extra parameters to add to the API call
945 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
946 * @return {jQuery.Promise} Promise that is resolved when the update is complete
948 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
949 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
951 if ( updateMode
=== this.FILTER_CHANGE
) {
952 this.uriProcessor
.updateURL( params
);
954 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
955 this.changesListModel
.invalidate();
957 this.changesListModel
.setNewChangesExist( false );
958 this.updatingChangesList
= true;
959 return this._fetchChangesList()
962 function ( pieces
) {
963 var $changesListContent
= pieces
.changes
,
964 $fieldset
= pieces
.fieldset
;
965 this.changesListModel
.update(
968 pieces
.noResultsDetails
,
970 // separator between old and new changes
971 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
974 // Do nothing for failure
976 .always( function () {
977 this.updatingChangesList
= false;
982 * Get an object representing the default parameter state, whether
983 * it is from the model defaults or from the saved queries.
985 * @return {Object} Default parameters
987 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
988 if ( this.savedQueriesModel
.getDefault() ) {
989 return this.savedQueriesModel
.getDefaultParams();
991 return this.filtersModel
.getDefaultParams();
996 * Query the list of changes from the server for the current filters
998 * @param {string} counterId Id for this request. To allow concurrent requests
999 * not to invalidate each other.
1000 * @param {Object} [params={}] Parameters to add to the query
1002 * @return {jQuery.Promise} Promise object resolved with { content, status }
1004 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1005 var uri
= this.uriProcessor
.getUpdatedUri(),
1006 stickyParams
= this.filtersModel
.getStickyParamsValues(),
1010 params
= params
|| {};
1011 params
.action
= 'render'; // bypasses MW chrome
1013 uri
.extend( params
);
1015 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1016 requestId
= ++this.requestCounter
[ counterId
];
1017 latestRequest = function () {
1018 return requestId
=== this.requestCounter
[ counterId
];
1021 // Sticky parameters override the URL params
1022 // this is to make sure that whether we represent
1023 // the sticky params in the URL or not (they may
1024 // be normalized out) the sticky parameters are
1025 // always being sent to the server with their
1026 // current/default values
1027 uri
.extend( stickyParams
);
1029 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1031 function ( content
, message
, jqXHR
) {
1032 if ( !latestRequest() ) {
1033 return $.Deferred().reject();
1037 status
: jqXHR
.status
1040 // RC returns 404 when there is no results
1041 function ( jqXHR
) {
1042 if ( latestRequest() ) {
1043 return $.Deferred().resolve(
1045 content
: jqXHR
.responseText
,
1046 status
: jqXHR
.status
1055 * Fetch the list of changes from the server for the current filters
1057 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1060 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1061 return this._queryChangesList( 'updateChangesList' )
1066 // Status code 0 is not HTTP status code,
1067 // but is valid value of XMLHttpRequest status.
1068 // It is used for variety of network errors, for example
1069 // when an AJAX call was cancelled before getting the response
1070 if ( data
&& data
.status
=== 0 ) {
1072 changes
: 'NO_RESULTS',
1073 // We need empty result set, to avoid exceptions because of undefined value
1075 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1079 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1080 data
? data
.content
: ''
1083 return this._extractChangesListInfo( $parsed
, data
.status
);
1089 * Track usage of highlight feature
1091 * @param {string} action
1092 * @param {Array|Object|string} filters
1094 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1095 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1096 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1098 'event.ChangesListHighlights',
1102 userId
: mw
.user
.getId()
1108 * Track filter grouping usage
1110 * @param {string} action Action taken
1112 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1113 var controller
= this,
1114 rightNow
= new Date().getTime(),
1115 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1116 // Get all current filters
1117 filters
= this.filtersModel
.findSelectedItems().map( function ( item
) {
1118 return item
.getName();
1121 action
= action
|| 'filtermenu';
1123 // Check if these filters were the ones we just logged previously
1124 // (Don't log the same grouping twice, in case the user opens/closes)
1125 // the menu without action, or with the same result
1127 // Only log if the two arrays are different in size
1128 filters
.length
!== this.prevLoggedItems
.length
||
1129 // Or if any filters are not the same as the cached filters
1130 filters
.some( function ( filterName
) {
1131 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1133 // Or if any cached filters are not the same as given filters
1134 this.prevLoggedItems
.some( function ( filterName
) {
1135 return filters
.indexOf( filterName
) === -1;
1138 filters
.forEach( function ( filterName
) {
1140 'event.ChangesListFilterGrouping',
1143 groupIdentifier
: randomIdentifier
,
1145 userId
: mw
.user
.getId()
1150 // Cache the filter names
1151 this.prevLoggedItems
= filters
;
1156 * Apply a change of parameters to the model state, and check whether
1157 * the new state is different than the old state.
1159 * @param {Object} newParamState New parameter state to apply
1160 * @return {boolean} New applied model state is different than the previous state
1162 mw
.rcfilters
.Controller
.prototype.applyParamChange = function ( newParamState
) {
1164 before
= this.filtersModel
.getSelectedState();
1166 this.filtersModel
.updateStateFromParams( newParamState
);
1168 after
= this.filtersModel
.getSelectedState();
1170 return !OO
.compare( before
, after
);
1174 * Mark all changes as seen on Watchlist
1176 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1177 var api
= new mw
.Api();
1178 api
.postWithToken( 'csrf', {
1180 action
: 'setnotificationtimestamp',
1181 entirewatchlist
: true
1182 } ).then( function () {
1183 this.updateChangesList( null, 'markSeen' );
1188 * Set the current search for the system.
1190 * @param {string} searchQuery Search query, including triggers
1192 mw
.rcfilters
.Controller
.prototype.setSearch = function ( searchQuery
) {
1193 this.filtersModel
.setSearch( searchQuery
);
1197 * Switch the view by changing the search query trigger
1198 * without changing the search term
1200 * @param {string} view View to change to
1202 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
1204 this.filtersModel
.getViewTrigger( view
) +
1205 this.filtersModel
.removeViewTriggers( this.filtersModel
.getSearch() )
1210 * Reset the search for a specific view. This means we null the search query
1211 * and replace it with the relevant trigger for the requested view
1213 * @param {string} [view='default'] View to change to
1215 mw
.rcfilters
.Controller
.prototype.resetSearchForView = function ( view
) {
1216 view
= view
|| 'default';
1219 this.filtersModel
.getViewTrigger( view
)