1 var byteLength
= require( 'mediawiki.String' ).byteLength
,
2 UriProcessor
= require( './UriProcessor.js' ),
5 /* eslint no-underscore-dangle: "off" */
7 * Controller for the filters in Recent Changes
8 * @class mw.rcfilters.Controller
11 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
12 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
13 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
14 * @param {Object} config Additional configuration
15 * @cfg {string} savedQueriesPreferenceName Where to save the saved queries
16 * @cfg {string} daysPreferenceName Preference name for the days filter
17 * @cfg {string} limitPreferenceName Preference name for the limit filter
18 * @cfg {string} collapsedPreferenceName Preference name for collapsing and showing
19 * the active filters area
20 * @cfg {boolean} [normalizeTarget] Dictates whether or not to go through the
21 * title normalization to separate title subpage/parts into the target= url
24 Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
, config
) {
25 this.filtersModel
= filtersModel
;
26 this.changesListModel
= changesListModel
;
27 this.savedQueriesModel
= savedQueriesModel
;
28 this.savedQueriesPreferenceName
= config
.savedQueriesPreferenceName
;
29 this.daysPreferenceName
= config
.daysPreferenceName
;
30 this.limitPreferenceName
= config
.limitPreferenceName
;
31 this.collapsedPreferenceName
= config
.collapsedPreferenceName
;
32 this.normalizeTarget
= !!config
.normalizeTarget
;
34 this.pollingRate
= require( './config.json' ).StructuredChangeFiltersLiveUpdatePollingRate
;
36 this.requestCounter
= {};
37 this.baseFilterState
= {};
38 this.uriProcessor
= null;
39 this.initialized
= false;
40 this.wereSavedQueriesSaved
= false;
42 this.prevLoggedItems
= [];
44 this.FILTER_CHANGE
= 'filterChange';
45 this.SHOW_NEW_CHANGES
= 'showNewChanges';
46 this.LIVE_UPDATE
= 'liveUpdate';
50 OO
.initClass( Controller
);
53 * Initialize the filter and parameter states
55 * @param {Array} filterStructure Filter definition and structure for the model
56 * @param {Object} [namespaceStructure] Namespace definition
57 * @param {Object} [tagList] Tag definition
58 * @param {Object} [conditionalViews] Conditional view definition
60 Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
, conditionalViews
) {
61 var parsedSavedQueries
, pieces
,
62 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
63 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
65 views
= $.extend( true, {}, conditionalViews
),
70 if ( namespaceStructure
) {
72 // eslint-disable-next-line no-jquery/no-each-util
73 $.each( namespaceStructure
, function ( namespaceID
, label
) {
74 // Build and clean up the individual namespace items definition
77 label
: label
|| mw
.msg( 'blanknamespace' ),
80 mw
.Title
.isTalkNamespace( namespaceID
) ?
83 cssClass
: 'mw-changeslist-ns-' + namespaceID
88 title
: mw
.msg( 'namespaces' ),
91 // Group definition (single group)
92 name
: 'namespace', // parameter name is singular
93 type
: 'string_options',
94 title
: mw
.msg( 'namespaces' ),
95 labelPrefixKey
: { default: 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
116 title
: mw
.msg( 'rcfilters-view-tags' ),
119 // Group definition (single group)
120 name
: 'tagfilter', // Parameter name
121 type
: 'string_options',
122 title
: 'rcfilters-view-tags', // Message key
123 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
131 // Add parameter range operations
136 type
: 'single_option',
137 title
: '', // Because it's a hidden group, this title actually appears nowhere
139 allowArbitrary
: true,
140 // FIXME: $.isNumeric is deprecated
141 validate
: $.isNumeric
,
143 min
: 0, // The server normalizes negative numbers to 0 results
146 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
147 default: mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
149 filters
: displayConfig
.limitArray
.map( function ( num
) {
150 return controller
._createFilterDataFromNumber( num
, num
);
155 type
: 'single_option',
156 title
: '', // Because it's a hidden group, this title actually appears nowhere
158 allowArbitrary
: true,
159 // FIXME: $.isNumeric is deprecated
160 validate
: $.isNumeric
,
163 max
: displayConfig
.maxDays
165 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
166 numToLabelFunc: function ( i
) {
167 return Number( i
) < 1 ?
168 ( Number( i
) * 24 ).toFixed( 2 ) :
171 default: mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
174 // Hours (1, 2, 6, 12)
175 0.04166, 0.0833, 0.25, 0.5
177 ].concat( displayConfig
.daysArray
)
178 .map( function ( num
) {
179 return controller
._createFilterDataFromNumber(
181 // Convert fractions of days to number of hours for the labels
182 num
< 1 ? Math
.round( num
* 24 ) : num
194 title
: '', // Because it's a hidden group, this title actually appears nowhere
200 default: String( mw
.user
.options
.get( 'usenewrc', 0 ) )
207 // Before we do anything, we need to see if we require additional items in the
208 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
209 // groups; if we ever expand it, this might need further generalization:
210 // eslint-disable-next-line no-jquery/no-each-util
211 $.each( views
, function ( viewName
, viewData
) {
212 viewData
.groups
.forEach( function ( groupData
) {
213 var extraValues
= [];
214 if ( groupData
.allowArbitrary
) {
215 // If the value in the URI isn't in the group, add it
216 if ( uri
.query
[ groupData
.name
] !== undefined ) {
217 extraValues
.push( uri
.query
[ groupData
.name
] );
219 // If the default value isn't in the group, add it
220 if ( groupData
.default !== undefined ) {
221 extraValues
.push( String( groupData
.default ) );
223 controller
.addNumberValuesToGroup( groupData
, extraValues
);
228 // Initialize the model
229 this.filtersModel
.initializeFilters( filterStructure
, views
);
231 this.uriProcessor
= new UriProcessor(
233 { normalizeTarget
: this.normalizeTarget
}
236 if ( !mw
.user
.isAnon() ) {
238 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
240 parsedSavedQueries
= {};
243 // Initialize saved queries
244 this.savedQueriesModel
.initialize( parsedSavedQueries
);
245 if ( this.savedQueriesModel
.isConverted() ) {
246 // Since we know we converted, we're going to re-save
247 // the queries so they are now migrated to the new format
248 this._saveSavedQueries();
252 if ( defaultSavedQueryExists
) {
253 // This came from the server, meaning that we have a default
254 // saved query, but the server could not load it, probably because
255 // it was pre-conversion to the new format.
256 // We need to load this query again
257 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
259 // There are either recognized parameters in the URL
260 // or there are none, but there is also no default
261 // saved query (so defaults are from the backend)
262 // We want to update the state but not fetch results
264 this.updateStateFromUrl( false );
266 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
268 // Update the changes list with the existing data
269 // so it gets processed
270 this.changesListModel
.update(
273 pieces
.noResultsDetails
,
274 true // We're using existing DOM elements
278 this.initialized
= true;
279 this.switchView( 'default' );
281 if ( this.pollingRate
) {
282 this._scheduleLiveUpdate();
287 * Check if the controller has finished initializing.
288 * @return {boolean} Controller is initialized
290 Controller
.prototype.isInitialized = function () {
291 return this.initialized
;
295 * Extracts information from the changes list DOM
297 * @param {jQuery} $root Root DOM to find children from
298 * @param {boolean} [statusCode] Server response status code
299 * @return {Object} Information about changes list
300 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
301 * (either normally or as an error)
302 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
303 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
304 * @return {jQuery} return.fieldset Fieldset
306 Controller
.prototype._extractChangesListInfo = function ( $root
, statusCode
) {
308 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
309 areResults
= !!$changesListContents
.length
,
310 checkForLogout
= !areResults
&& statusCode
=== 200;
312 // We check if user logged out on different tab/browser or the session has expired.
313 // 205 status code returned from the server, which indicates that we need to reload the page
314 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
315 // status code (if everything else goes well).
317 if ( checkForLogout
&& !!$root
.find( '#wpName1' ).length
) {
318 location
.reload( false );
323 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
324 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
328 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
329 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
330 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
331 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
332 } else if ( $root
.find( '.mw-changeslist-invalidtargetpage' ).length
) {
333 info
.noResultsDetails
= 'NO_RESULTS_INVALID_TARGET_PAGE';
335 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
343 * Create filter data from a number, for the filters that are numerical value
345 * @param {number} num Number
346 * @param {number} numForDisplay Number for the label
347 * @return {Object} Filter data
349 Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
352 label
: mw
.language
.convertNumber( numForDisplay
)
357 * Add an arbitrary values to groups that allow arbitrary values
359 * @param {Object} groupData Group data
360 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
362 Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
363 var controller
= this,
364 normalizeWithinRange = function ( range
, val
) {
365 if ( val
< range
.min
) {
366 return range
.min
; // Min
367 } else if ( val
>= range
.max
) {
368 return range
.max
; // Max
373 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
375 // Normalize the arbitrary values and the default value for a range
376 if ( groupData
.range
) {
377 arbitraryValues
= arbitraryValues
.map( function ( val
) {
378 return normalizeWithinRange( groupData
.range
, val
);
381 // Normalize the default, since that's user defined
382 if ( groupData
.default !== undefined ) {
383 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
387 // This is only true for single_option group
388 // We assume these are the only groups that will allow for
389 // arbitrary, since it doesn't make any sense for the other
391 arbitraryValues
.forEach( function ( val
) {
393 // If the group allows for arbitrary data
394 groupData
.allowArbitrary
&&
395 // and it is single_option (or string_options, but we
396 // don't have cases of those yet, nor do we plan to)
397 groupData
.type
=== 'single_option' &&
398 // and, if there is a validate method and it passes on
400 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
401 // but if that value isn't already in the definition
403 .map( function ( filterData
) {
404 return String( filterData
.name
);
406 .indexOf( String( val
) ) === -1
408 // Add the filter information
409 groupData
.filters
.push( controller
._createFilterDataFromNumber(
411 groupData
.numToLabelFunc
?
412 groupData
.numToLabelFunc( val
) :
416 // If there's a sort function set up, re-sort the values
417 if ( groupData
.sortFunc
) {
418 groupData
.filters
.sort( groupData
.sortFunc
);
425 * Reset to default filters
427 Controller
.prototype.resetToDefaults = function () {
428 var params
= this._getDefaultParams();
429 if ( this.applyParamChange( params
) ) {
430 // Only update the changes list if there was a change to actual filters
431 this.updateChangesList();
433 this.uriProcessor
.updateURL( params
);
438 * Check whether the default values of the filters are all false.
440 * @return {boolean} Defaults are all false
442 Controller
.prototype.areDefaultsEmpty = function () {
443 return $.isEmptyObject( this._getDefaultParams() );
447 * Empty all selected filters
449 Controller
.prototype.emptyFilters = function () {
450 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
451 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
453 if ( this.applyParamChange( {} ) ) {
454 // Only update the changes list if there was a change to actual filters
455 this.updateChangesList();
457 this.uriProcessor
.updateURL();
460 if ( highlightedFilterNames
) {
461 this._trackHighlight( 'clearAll', highlightedFilterNames
);
466 * Update the selected state of a filter
468 * @param {string} filterName Filter name
469 * @param {boolean} [isSelected] Filter selected state
471 Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
472 var filterItem
= this.filtersModel
.getItemByName( filterName
);
475 // If no filter was found, break
479 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
481 if ( filterItem
.isSelected() !== isSelected
) {
482 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
484 this.updateChangesList();
486 // Check filter interactions
487 this.filtersModel
.reassessFilterInteractions( filterItem
);
492 * Clear both highlight and selection of a filter
494 * @param {string} filterName Name of the filter item
496 Controller
.prototype.clearFilter = function ( filterName
) {
497 var filterItem
= this.filtersModel
.getItemByName( filterName
),
498 isHighlighted
= filterItem
.isHighlighted(),
499 isSelected
= filterItem
.isSelected();
501 if ( isSelected
|| isHighlighted
) {
502 this.filtersModel
.clearHighlightColor( filterName
);
503 this.filtersModel
.toggleFilterSelected( filterName
, false );
506 // Only update the changes list if the filter changed
507 // its selection state. If it only changed its highlight
509 this.updateChangesList();
512 this.filtersModel
.reassessFilterInteractions( filterItem
);
514 // Log filter grouping
515 this.trackFilterGroupings( 'removefilter' );
518 if ( isHighlighted
) {
519 this._trackHighlight( 'clear', filterName
);
524 * Toggle the highlight feature on and off
526 Controller
.prototype.toggleHighlight = function () {
527 this.filtersModel
.toggleHighlight();
528 this.uriProcessor
.updateURL();
530 if ( this.filtersModel
.isHighlightEnabled() ) {
531 mw
.hook( 'RcFilters.highlight.enable' ).fire();
536 * Toggle the namespaces inverted feature on and off
538 Controller
.prototype.toggleInvertedNamespaces = function () {
539 this.filtersModel
.toggleInvertedNamespaces();
541 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
542 function ( filterItem
) { return filterItem
.isSelected(); }
545 // Only re-fetch results if there are namespace items that are actually selected
546 this.updateChangesList();
548 this.uriProcessor
.updateURL();
553 * Set the value of the 'showlinkedto' parameter
554 * @param {boolean} value
556 Controller
.prototype.setShowLinkedTo = function ( value
) {
557 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
558 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
560 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
561 this.uriProcessor
.updateURL();
562 // reload the results only when target is set
563 if ( targetItem
.getValue() ) {
564 this.updateChangesList();
569 * Set the target page
570 * @param {string} page
572 Controller
.prototype.setTargetPage = function ( page
) {
573 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
574 targetItem
.setValue( page
);
575 this.uriProcessor
.updateURL();
576 this.updateChangesList();
580 * Set the highlight color for a filter item
582 * @param {string} filterName Name of the filter item
583 * @param {string} color Selected color
585 Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
586 this.filtersModel
.setHighlightColor( filterName
, color
);
587 this.uriProcessor
.updateURL();
588 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
592 * Clear highlight for a filter item
594 * @param {string} filterName Name of the filter item
596 Controller
.prototype.clearHighlightColor = function ( filterName
) {
597 this.filtersModel
.clearHighlightColor( filterName
);
598 this.uriProcessor
.updateURL();
599 this._trackHighlight( 'clear', filterName
);
603 * Enable or disable live updates.
604 * @param {boolean} enable True to enable, false to disable
606 Controller
.prototype.toggleLiveUpdate = function ( enable
) {
607 this.changesListModel
.toggleLiveUpdate( enable
);
608 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
609 this.updateChangesList( null, this.LIVE_UPDATE
);
614 * Set a timeout for the next live update.
617 Controller
.prototype._scheduleLiveUpdate = function () {
618 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
622 * Perform a live update.
625 Controller
.prototype._doLiveUpdate = function () {
626 if ( !this._shouldCheckForNewChanges() ) {
627 // skip this turn and check back later
628 this._scheduleLiveUpdate();
632 this._checkForNewChanges()
633 .then( function ( statusCode
) {
634 // no result is 204 with the 'peek' param
636 var newChanges
= statusCode
=== 200;
638 if ( !this._shouldCheckForNewChanges() ) {
639 // by the time the response is received,
640 // it may not be appropriate anymore
644 // 205 is the status code returned from server when user's logged in/out
645 // status is not matching while fetching live update changes.
646 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
648 if ( statusCode
=== 205 ) {
649 location
.reload( false );
654 if ( this.changesListModel
.getLiveUpdate() ) {
655 return this.updateChangesList( null, this.LIVE_UPDATE
);
657 this.changesListModel
.setNewChangesExist( true );
661 .always( this._scheduleLiveUpdate
.bind( this ) );
665 * @return {boolean} It's appropriate to check for new changes now
668 Controller
.prototype._shouldCheckForNewChanges = function () {
669 return !document
.hidden
&&
670 !this.filtersModel
.hasConflict() &&
671 !this.changesListModel
.getNewChangesExist() &&
672 !this.updatingChangesList
&&
673 this.changesListModel
.getNextFrom();
677 * Check if new changes, newer than those currently shown, are available
679 * @return {jQuery.Promise} Promise object that resolves with a bool
680 * specifying if there are new changes or not
684 Controller
.prototype._checkForNewChanges = function () {
687 peek
: 1, // bypasses ChangesList specific UI
688 from: this.changesListModel
.getNextFrom(),
689 isAnon
: mw
.user
.isAnon()
691 return this._queryChangesList( 'liveUpdate', params
).then(
699 * Show the new changes
701 * @return {jQuery.Promise} Promise object that resolves after
702 * fetching and showing the new changes
704 Controller
.prototype.showNewChanges = function () {
705 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
709 * Save the current model state as a saved query
711 * @param {string} [label] Label of the saved query
712 * @param {boolean} [setAsDefault=false] This query should be set as the default
714 Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
716 this.savedQueriesModel
.addNewQuery(
717 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
718 this.filtersModel
.getCurrentParameterState( true ),
723 this._saveSavedQueries();
727 * Remove a saved query
729 * @param {string} queryID Query id
731 Controller
.prototype.removeSavedQuery = function ( queryID
) {
732 this.savedQueriesModel
.removeQuery( queryID
);
734 this._saveSavedQueries();
738 * Rename a saved query
740 * @param {string} queryID Query id
741 * @param {string} newLabel New label for the query
743 Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
744 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
747 queryItem
.updateLabel( newLabel
);
749 this._saveSavedQueries();
753 * Set a saved query as default
755 * @param {string} queryID Query Id. If null is given, default
758 Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
759 this.savedQueriesModel
.setDefault( queryID
);
760 this._saveSavedQueries();
766 * @param {string} queryID Query id
768 Controller
.prototype.applySavedQuery = function ( queryID
) {
769 var currentMatchingQuery
,
770 params
= this.savedQueriesModel
.getItemParams( queryID
);
772 currentMatchingQuery
= this.findQueryMatchingCurrentState();
775 currentMatchingQuery
&&
776 currentMatchingQuery
.getID() === queryID
778 // If the query we want to load is the one that is already
779 // loaded, don't reload it
783 if ( this.applyParamChange( params
) ) {
784 // Update changes list only if there was a difference in filter selection
785 this.updateChangesList();
787 this.uriProcessor
.updateURL( params
);
790 // Log filter grouping
791 this.trackFilterGroupings( 'savedfilters' );
795 * Check whether the current filter and highlight state exists
796 * in the saved queries model.
798 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
800 Controller
.prototype.findQueryMatchingCurrentState = function () {
801 return this.savedQueriesModel
.findMatchingQuery(
802 this.filtersModel
.getCurrentParameterState( true )
807 * Save the current state of the saved queries model with all
808 * query item representation in the user settings.
810 Controller
.prototype._saveSavedQueries = function () {
811 var stringified
, oldPrefValue
,
812 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
813 state
= this.savedQueriesModel
.getState();
816 stringified
= JSON
.stringify( state
);
818 if ( byteLength( stringified
) > 65535 ) {
819 // Sanity check, since the preference can only hold that.
823 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
824 // The queries were converted from the previous version
825 // Keep the old string in the [prefname]-versionbackup
826 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
828 // Save the old preference in the backup preference
829 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
830 // Update the preference for this session
831 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
834 // Save the preference
835 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
836 // Update the preference for this session
837 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
839 // Tag as already saved so we don't do this again
840 this.wereSavedQueriesSaved
= true;
844 * Update sticky preferences with current model state
846 Controller
.prototype.updateStickyPreferences = function () {
847 // Update default sticky values with selected, whether they came from
848 // the initial defaults or from the URL value that is being normalized
849 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).findSelectedItems()[ 0 ].getParamName() );
850 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).findSelectedItems()[ 0 ].getParamName() );
852 // TODO: Make these automatic by having the model go over sticky
853 // items and update their default values automatically
857 * Update the limit default value
859 * @param {number} newValue New value
861 Controller
.prototype.updateLimitDefault = function ( newValue
) {
862 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
866 * Update the days default value
868 * @param {number} newValue New value
870 Controller
.prototype.updateDaysDefault = function ( newValue
) {
871 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
875 * Update the group by page default value
877 * @param {boolean} newValue New value
879 Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
880 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
884 * Update the collapsed state value
886 * @param {boolean} isCollapsed Filter area is collapsed
888 Controller
.prototype.updateCollapsedState = function ( isCollapsed
) {
889 this.updateNumericPreference( this.collapsedPreferenceName
, Number( isCollapsed
) );
893 * Update a numeric preference with a new value
895 * @param {string} prefName Preference name
896 * @param {number|string} newValue New value
898 Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
899 // FIXME: $.isNumeric is deprecated
900 // eslint-disable-next-line no-jquery/no-is-numeric
901 if ( !$.isNumeric( newValue
) ) {
905 newValue
= Number( newValue
);
907 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
908 // Save the preference
909 new mw
.Api().saveOption( prefName
, newValue
);
910 // Update the preference for this session
911 mw
.user
.options
.set( prefName
, newValue
);
916 * Synchronize the URL with the current state of the filters
917 * without adding an history entry.
919 Controller
.prototype.replaceUrl = function () {
920 this.uriProcessor
.updateURL();
924 * Update filter state (selection and highlighting) based
925 * on current URL values.
927 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
928 * list based on the updated model.
930 Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
931 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
933 this.uriProcessor
.updateModelBasedOnQuery();
935 // Update the sticky preferences, in case we received a value
937 this.updateStickyPreferences();
939 // Only update and fetch new results if it is requested
940 if ( fetchChangesList
) {
941 this.updateChangesList();
946 * Update the list of changes and notify the model
948 * @param {Object} [params] Extra parameters to add to the API call
949 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
950 * @return {jQuery.Promise} Promise that is resolved when the update is complete
952 Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
953 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
955 if ( updateMode
=== this.FILTER_CHANGE
) {
956 this.uriProcessor
.updateURL( params
);
958 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
959 this.changesListModel
.invalidate();
961 this.changesListModel
.setNewChangesExist( false );
962 this.updatingChangesList
= true;
963 return this._fetchChangesList()
966 function ( pieces
) {
967 var $changesListContent
= pieces
.changes
,
968 $fieldset
= pieces
.fieldset
;
969 this.changesListModel
.update(
972 pieces
.noResultsDetails
,
974 // separator between old and new changes
975 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
978 // Do nothing for failure
980 .always( function () {
981 this.updatingChangesList
= false;
986 * Get an object representing the default parameter state, whether
987 * it is from the model defaults or from the saved queries.
989 * @return {Object} Default parameters
991 Controller
.prototype._getDefaultParams = function () {
992 if ( this.savedQueriesModel
.getDefault() ) {
993 return this.savedQueriesModel
.getDefaultParams();
995 return this.filtersModel
.getDefaultParams();
1000 * Query the list of changes from the server for the current filters
1002 * @param {string} counterId Id for this request. To allow concurrent requests
1003 * not to invalidate each other.
1004 * @param {Object} [params={}] Parameters to add to the query
1006 * @return {jQuery.Promise} Promise object resolved with { content, status }
1008 Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1009 var uri
= this.uriProcessor
.getUpdatedUri(),
1010 stickyParams
= this.filtersModel
.getStickyParamsValues(),
1014 params
= params
|| {};
1015 params
.action
= 'render'; // bypasses MW chrome
1017 uri
.extend( params
);
1019 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1020 requestId
= ++this.requestCounter
[ counterId
];
1021 latestRequest = function () {
1022 return requestId
=== this.requestCounter
[ counterId
];
1025 // Sticky parameters override the URL params
1026 // this is to make sure that whether we represent
1027 // the sticky params in the URL or not (they may
1028 // be normalized out) the sticky parameters are
1029 // always being sent to the server with their
1030 // current/default values
1031 uri
.extend( stickyParams
);
1033 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1035 function ( content
, message
, jqXHR
) {
1036 if ( !latestRequest() ) {
1037 return $.Deferred().reject();
1041 status
: jqXHR
.status
1044 // RC returns 404 when there is no results
1045 function ( jqXHR
) {
1046 if ( latestRequest() ) {
1047 return $.Deferred().resolve(
1049 content
: jqXHR
.responseText
,
1050 status
: jqXHR
.status
1059 * Fetch the list of changes from the server for the current filters
1061 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1064 Controller
.prototype._fetchChangesList = function () {
1065 return this._queryChangesList( 'updateChangesList' )
1070 // Status code 0 is not HTTP status code,
1071 // but is valid value of XMLHttpRequest status.
1072 // It is used for variety of network errors, for example
1073 // when an AJAX call was cancelled before getting the response
1074 if ( data
&& data
.status
=== 0 ) {
1076 changes
: 'NO_RESULTS',
1077 // We need empty result set, to avoid exceptions because of undefined value
1079 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1083 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1084 data
? data
.content
: ''
1087 return this._extractChangesListInfo( $parsed
, data
.status
);
1093 * Track usage of highlight feature
1095 * @param {string} action
1096 * @param {Array|Object|string} filters
1098 Controller
.prototype._trackHighlight = function ( action
, filters
) {
1099 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1100 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1102 'event.ChangesListHighlights',
1106 userId
: mw
.user
.getId()
1112 * Track filter grouping usage
1114 * @param {string} action Action taken
1116 Controller
.prototype.trackFilterGroupings = function ( action
) {
1117 var controller
= this,
1118 rightNow
= new Date().getTime(),
1119 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1120 // Get all current filters
1121 filters
= this.filtersModel
.findSelectedItems().map( function ( item
) {
1122 return item
.getName();
1125 action
= action
|| 'filtermenu';
1127 // Check if these filters were the ones we just logged previously
1128 // (Don't log the same grouping twice, in case the user opens/closes)
1129 // the menu without action, or with the same result
1131 // Only log if the two arrays are different in size
1132 filters
.length
!== this.prevLoggedItems
.length
||
1133 // Or if any filters are not the same as the cached filters
1134 filters
.some( function ( filterName
) {
1135 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1137 // Or if any cached filters are not the same as given filters
1138 this.prevLoggedItems
.some( function ( filterName
) {
1139 return filters
.indexOf( filterName
) === -1;
1142 filters
.forEach( function ( filterName
) {
1144 'event.ChangesListFilterGrouping',
1147 groupIdentifier
: randomIdentifier
,
1149 userId
: mw
.user
.getId()
1154 // Cache the filter names
1155 this.prevLoggedItems
= filters
;
1160 * Apply a change of parameters to the model state, and check whether
1161 * the new state is different than the old state.
1163 * @param {Object} newParamState New parameter state to apply
1164 * @return {boolean} New applied model state is different than the previous state
1166 Controller
.prototype.applyParamChange = function ( newParamState
) {
1168 before
= this.filtersModel
.getSelectedState();
1170 this.filtersModel
.updateStateFromParams( newParamState
);
1172 after
= this.filtersModel
.getSelectedState();
1174 return !OO
.compare( before
, after
);
1178 * Mark all changes as seen on Watchlist
1180 Controller
.prototype.markAllChangesAsSeen = function () {
1181 var api
= new mw
.Api();
1182 api
.postWithToken( 'csrf', {
1184 action
: 'setnotificationtimestamp',
1185 entirewatchlist
: true
1186 } ).then( function () {
1187 this.updateChangesList( null, 'markSeen' );
1192 * Set the current search for the system.
1194 * @param {string} searchQuery Search query, including triggers
1196 Controller
.prototype.setSearch = function ( searchQuery
) {
1197 this.filtersModel
.setSearch( searchQuery
);
1201 * Switch the view by changing the search query trigger
1202 * without changing the search term
1204 * @param {string} view View to change to
1206 Controller
.prototype.switchView = function ( view
) {
1208 this.filtersModel
.getViewTrigger( view
) +
1209 this.filtersModel
.removeViewTriggers( this.filtersModel
.getSearch() )
1214 * Reset the search for a specific view. This means we null the search query
1215 * and replace it with the relevant trigger for the requested view
1217 * @param {string} [view='default'] View to change to
1219 Controller
.prototype.resetSearchForView = function ( view
) {
1220 view
= view
|| 'default';
1223 this.filtersModel
.getViewTrigger( view
)
1227 module
.exports
= Controller
;