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.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( 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 Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
, conditionalViews
) {
60 var parsedSavedQueries
, pieces
,
61 nsAllContents
, nsAllDiscussions
,
62 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
63 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
65 views
= $.extend( true, {}, conditionalViews
),
70 if ( namespaceStructure
) {
73 label
: mw
.msg( 'rcfilters-allcontents-label' ),
75 identifiers
: [ 'subject' ],
76 cssClass
: 'mw-changeslist-ns-subject',
80 name
: 'all-discussions',
81 label
: mw
.msg( 'rcfilters-alldiscussions-label' ),
83 identifiers
: [ 'talk' ],
84 cssClass
: 'mw-changeslist-ns-talk',
87 items
= [ nsAllContents
, nsAllDiscussions
];
88 // eslint-disable-next-line no-jquery/no-each-util
89 $.each( namespaceStructure
, function ( namespaceID
, label
) {
90 // Build and clean up the individual namespace items definition
91 var isTalk
= mw
.Title
.isTalkNamespace( namespaceID
),
94 label
: label
|| mw
.msg( 'blanknamespace' ),
97 isTalk
? 'talk' : 'subject'
99 cssClass
: 'mw-changeslist-ns-' + namespaceID
101 items
.push( nsFilter
);
102 ( isTalk
? nsAllDiscussions
: nsAllContents
).subset
.push( { filter
: namespaceID
} );
106 title
: mw
.msg( 'namespaces' ),
109 // Group definition (single group)
110 name
: 'namespace', // parameter name is singular
111 type
: 'string_options',
112 title
: mw
.msg( 'namespaces' ),
113 labelPrefixKey
: { default: 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
134 title
: mw
.msg( 'rcfilters-view-tags' ),
137 // Group definition (single group)
138 name
: 'tagfilter', // Parameter name
139 type
: 'string_options',
140 title
: 'rcfilters-view-tags', // Message key
141 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
149 // Add parameter range operations
154 type
: 'single_option',
155 title
: '', // Because it's a hidden group, this title actually appears nowhere
157 allowArbitrary
: true,
158 // FIXME: $.isNumeric is deprecated
159 validate
: $.isNumeric
,
161 min
: 0, // The server normalizes negative numbers to 0 results
164 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
165 default: mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
167 filters
: displayConfig
.limitArray
.map( function ( num
) {
168 return controller
._createFilterDataFromNumber( num
, num
);
173 type
: 'single_option',
174 title
: '', // Because it's a hidden group, this title actually appears nowhere
176 allowArbitrary
: true,
177 // FIXME: $.isNumeric is deprecated
178 validate
: $.isNumeric
,
181 max
: displayConfig
.maxDays
183 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
184 numToLabelFunc: function ( i
) {
185 return Number( i
) < 1 ?
186 ( Number( i
) * 24 ).toFixed( 2 ) :
189 default: mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
192 // Hours (1, 2, 6, 12)
193 0.04166, 0.0833, 0.25, 0.5
195 ].concat( displayConfig
.daysArray
)
196 .map( function ( num
) {
197 return controller
._createFilterDataFromNumber(
199 // Convert fractions of days to number of hours for the labels
200 num
< 1 ? Math
.round( num
* 24 ) : num
212 title
: '', // Because it's a hidden group, this title actually appears nowhere
218 default: String( mw
.user
.options
.get( 'usenewrc', 0 ) )
225 // Before we do anything, we need to see if we require additional items in the
226 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
227 // groups; if we ever expand it, this might need further generalization:
228 // eslint-disable-next-line no-jquery/no-each-util
229 $.each( views
, function ( viewName
, viewData
) {
230 viewData
.groups
.forEach( function ( groupData
) {
231 var extraValues
= [];
232 if ( groupData
.allowArbitrary
) {
233 // If the value in the URI isn't in the group, add it
234 if ( uri
.query
[ groupData
.name
] !== undefined ) {
235 extraValues
.push( uri
.query
[ groupData
.name
] );
237 // If the default value isn't in the group, add it
238 if ( groupData
.default !== undefined ) {
239 extraValues
.push( String( groupData
.default ) );
241 controller
.addNumberValuesToGroup( groupData
, extraValues
);
246 // Initialize the model
247 this.filtersModel
.initializeFilters( filterStructure
, views
);
249 this.uriProcessor
= new UriProcessor(
251 { normalizeTarget
: this.normalizeTarget
}
254 if ( !mw
.user
.isAnon() ) {
256 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
258 parsedSavedQueries
= {};
261 // Initialize saved queries
262 this.savedQueriesModel
.initialize( parsedSavedQueries
);
263 if ( this.savedQueriesModel
.isConverted() ) {
264 // Since we know we converted, we're going to re-save
265 // the queries so they are now migrated to the new format
266 this._saveSavedQueries();
270 if ( defaultSavedQueryExists
) {
271 // This came from the server, meaning that we have a default
272 // saved query, but the server could not load it, probably because
273 // it was pre-conversion to the new format.
274 // We need to load this query again
275 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
277 // There are either recognized parameters in the URL
278 // or there are none, but there is also no default
279 // saved query (so defaults are from the backend)
280 // We want to update the state but not fetch results
282 this.updateStateFromUrl( false );
284 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
286 // Update the changes list with the existing data
287 // so it gets processed
288 this.changesListModel
.update(
291 pieces
.noResultsDetails
,
292 true // We're using existing DOM elements
296 this.initialized
= true;
297 this.switchView( 'default' );
299 if ( this.pollingRate
) {
300 this._scheduleLiveUpdate();
305 * Check if the controller has finished initializing.
306 * @return {boolean} Controller is initialized
308 Controller
.prototype.isInitialized = function () {
309 return this.initialized
;
313 * Extracts information from the changes list DOM
315 * @param {jQuery} $root Root DOM to find children from
316 * @param {boolean} [statusCode] Server response status code
317 * @return {Object} Information about changes list
318 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
319 * (either normally or as an error)
320 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
321 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
322 * @return {jQuery} return.fieldset Fieldset
324 Controller
.prototype._extractChangesListInfo = function ( $root
, statusCode
) {
326 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
327 areResults
= !!$changesListContents
.length
,
328 checkForLogout
= !areResults
&& statusCode
=== 200;
330 // We check if user logged out on different tab/browser or the session has expired.
331 // 205 status code returned from the server, which indicates that we need to reload the page
332 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
333 // status code (if everything else goes well).
335 if ( checkForLogout
&& !!$root
.find( '#wpName1' ).length
) {
336 location
.reload( false );
341 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
342 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
346 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
347 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
348 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
349 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
350 } else if ( $root
.find( '.mw-changeslist-invalidtargetpage' ).length
) {
351 info
.noResultsDetails
= 'NO_RESULTS_INVALID_TARGET_PAGE';
353 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
361 * Create filter data from a number, for the filters that are numerical value
363 * @param {number} num Number
364 * @param {number} numForDisplay Number for the label
365 * @return {Object} Filter data
367 Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
370 label
: mw
.language
.convertNumber( numForDisplay
)
375 * Add an arbitrary values to groups that allow arbitrary values
377 * @param {Object} groupData Group data
378 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
380 Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
381 var controller
= this,
382 normalizeWithinRange = function ( range
, val
) {
383 if ( val
< range
.min
) {
384 return range
.min
; // Min
385 } else if ( val
>= range
.max
) {
386 return range
.max
; // Max
391 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
393 // Normalize the arbitrary values and the default value for a range
394 if ( groupData
.range
) {
395 arbitraryValues
= arbitraryValues
.map( function ( val
) {
396 return normalizeWithinRange( groupData
.range
, val
);
399 // Normalize the default, since that's user defined
400 if ( groupData
.default !== undefined ) {
401 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
405 // This is only true for single_option group
406 // We assume these are the only groups that will allow for
407 // arbitrary, since it doesn't make any sense for the other
409 arbitraryValues
.forEach( function ( val
) {
411 // If the group allows for arbitrary data
412 groupData
.allowArbitrary
&&
413 // and it is single_option (or string_options, but we
414 // don't have cases of those yet, nor do we plan to)
415 groupData
.type
=== 'single_option' &&
416 // and, if there is a validate method and it passes on
418 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
419 // but if that value isn't already in the definition
421 .map( function ( filterData
) {
422 return String( filterData
.name
);
424 .indexOf( String( val
) ) === -1
426 // Add the filter information
427 groupData
.filters
.push( controller
._createFilterDataFromNumber(
429 groupData
.numToLabelFunc
?
430 groupData
.numToLabelFunc( val
) :
434 // If there's a sort function set up, re-sort the values
435 if ( groupData
.sortFunc
) {
436 groupData
.filters
.sort( groupData
.sortFunc
);
443 * Reset to default filters
445 Controller
.prototype.resetToDefaults = function () {
446 var params
= this._getDefaultParams();
447 if ( this.applyParamChange( params
) ) {
448 // Only update the changes list if there was a change to actual filters
449 this.updateChangesList();
451 this.uriProcessor
.updateURL( params
);
456 * Check whether the default values of the filters are all false.
458 * @return {boolean} Defaults are all false
460 Controller
.prototype.areDefaultsEmpty = function () {
461 return $.isEmptyObject( this._getDefaultParams() );
465 * Empty all selected filters
467 Controller
.prototype.emptyFilters = function () {
468 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
469 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
471 if ( this.applyParamChange( {} ) ) {
472 // Only update the changes list if there was a change to actual filters
473 this.updateChangesList();
475 this.uriProcessor
.updateURL();
478 if ( highlightedFilterNames
) {
479 this._trackHighlight( 'clearAll', highlightedFilterNames
);
484 * Update the selected state of a filter
486 * @param {string} filterName Filter name
487 * @param {boolean} [isSelected] Filter selected state
489 Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
490 var filterItem
= this.filtersModel
.getItemByName( filterName
);
493 // If no filter was found, break
497 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
499 if ( filterItem
.isSelected() !== isSelected
) {
500 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
502 this.updateChangesList();
504 // Check filter interactions
505 this.filtersModel
.reassessFilterInteractions( filterItem
);
510 * Clear both highlight and selection of a filter
512 * @param {string} filterName Name of the filter item
514 Controller
.prototype.clearFilter = function ( filterName
) {
515 var filterItem
= this.filtersModel
.getItemByName( filterName
),
516 isHighlighted
= filterItem
.isHighlighted(),
517 isSelected
= filterItem
.isSelected();
519 if ( isSelected
|| isHighlighted
) {
520 this.filtersModel
.clearHighlightColor( filterName
);
521 this.filtersModel
.toggleFilterSelected( filterName
, false );
524 // Only update the changes list if the filter changed
525 // its selection state. If it only changed its highlight
527 this.updateChangesList();
530 this.filtersModel
.reassessFilterInteractions( filterItem
);
532 // Log filter grouping
533 this.trackFilterGroupings( 'removefilter' );
536 if ( isHighlighted
) {
537 this._trackHighlight( 'clear', filterName
);
542 * Toggle the highlight feature on and off
544 Controller
.prototype.toggleHighlight = function () {
545 this.filtersModel
.toggleHighlight();
546 this.uriProcessor
.updateURL();
548 if ( this.filtersModel
.isHighlightEnabled() ) {
549 mw
.hook( 'RcFilters.highlight.enable' ).fire();
554 * Toggle the namespaces inverted feature on and off
556 Controller
.prototype.toggleInvertedNamespaces = function () {
557 this.filtersModel
.toggleInvertedNamespaces();
559 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
560 function ( filterItem
) { return filterItem
.isSelected(); }
563 // Only re-fetch results if there are namespace items that are actually selected
564 this.updateChangesList();
566 this.uriProcessor
.updateURL();
571 * Set the value of the 'showlinkedto' parameter
572 * @param {boolean} value
574 Controller
.prototype.setShowLinkedTo = function ( value
) {
575 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
576 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
578 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
579 this.uriProcessor
.updateURL();
580 // reload the results only when target is set
581 if ( targetItem
.getValue() ) {
582 this.updateChangesList();
587 * Set the target page
588 * @param {string} page
590 Controller
.prototype.setTargetPage = function ( page
) {
591 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
592 targetItem
.setValue( page
);
593 this.uriProcessor
.updateURL();
594 this.updateChangesList();
598 * Set the highlight color for a filter item
600 * @param {string} filterName Name of the filter item
601 * @param {string} color Selected color
603 Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
604 this.filtersModel
.setHighlightColor( filterName
, color
);
605 this.uriProcessor
.updateURL();
606 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
610 * Clear highlight for a filter item
612 * @param {string} filterName Name of the filter item
614 Controller
.prototype.clearHighlightColor = function ( filterName
) {
615 this.filtersModel
.clearHighlightColor( filterName
);
616 this.uriProcessor
.updateURL();
617 this._trackHighlight( 'clear', filterName
);
621 * Enable or disable live updates.
622 * @param {boolean} enable True to enable, false to disable
624 Controller
.prototype.toggleLiveUpdate = function ( enable
) {
625 this.changesListModel
.toggleLiveUpdate( enable
);
626 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
627 this.updateChangesList( null, this.LIVE_UPDATE
);
632 * Set a timeout for the next live update.
635 Controller
.prototype._scheduleLiveUpdate = function () {
636 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
640 * Perform a live update.
643 Controller
.prototype._doLiveUpdate = function () {
644 if ( !this._shouldCheckForNewChanges() ) {
645 // skip this turn and check back later
646 this._scheduleLiveUpdate();
650 this._checkForNewChanges()
651 .then( function ( statusCode
) {
652 // no result is 204 with the 'peek' param
654 var newChanges
= statusCode
=== 200;
656 if ( !this._shouldCheckForNewChanges() ) {
657 // by the time the response is received,
658 // it may not be appropriate anymore
662 // 205 is the status code returned from server when user's logged in/out
663 // status is not matching while fetching live update changes.
664 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
666 if ( statusCode
=== 205 ) {
667 location
.reload( false );
672 if ( this.changesListModel
.getLiveUpdate() ) {
673 return this.updateChangesList( null, this.LIVE_UPDATE
);
675 this.changesListModel
.setNewChangesExist( true );
679 .always( this._scheduleLiveUpdate
.bind( this ) );
683 * @return {boolean} It's appropriate to check for new changes now
686 Controller
.prototype._shouldCheckForNewChanges = function () {
687 return !document
.hidden
&&
688 !this.filtersModel
.hasConflict() &&
689 !this.changesListModel
.getNewChangesExist() &&
690 !this.updatingChangesList
&&
691 this.changesListModel
.getNextFrom();
695 * Check if new changes, newer than those currently shown, are available
697 * @return {jQuery.Promise} Promise object that resolves with a bool
698 * specifying if there are new changes or not
702 Controller
.prototype._checkForNewChanges = function () {
705 peek
: 1, // bypasses ChangesList specific UI
706 from: this.changesListModel
.getNextFrom(),
707 isAnon
: mw
.user
.isAnon()
709 return this._queryChangesList( 'liveUpdate', params
).then(
717 * Show the new changes
719 * @return {jQuery.Promise} Promise object that resolves after
720 * fetching and showing the new changes
722 Controller
.prototype.showNewChanges = function () {
723 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
727 * Save the current model state as a saved query
729 * @param {string} [label] Label of the saved query
730 * @param {boolean} [setAsDefault=false] This query should be set as the default
732 Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
734 this.savedQueriesModel
.addNewQuery(
735 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
736 this.filtersModel
.getCurrentParameterState( true ),
741 this._saveSavedQueries();
745 * Remove a saved query
747 * @param {string} queryID Query id
749 Controller
.prototype.removeSavedQuery = function ( queryID
) {
750 this.savedQueriesModel
.removeQuery( queryID
);
752 this._saveSavedQueries();
756 * Rename a saved query
758 * @param {string} queryID Query id
759 * @param {string} newLabel New label for the query
761 Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
762 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
765 queryItem
.updateLabel( newLabel
);
767 this._saveSavedQueries();
771 * Set a saved query as default
773 * @param {string} queryID Query Id. If null is given, default
776 Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
777 this.savedQueriesModel
.setDefault( queryID
);
778 this._saveSavedQueries();
784 * @param {string} queryID Query id
786 Controller
.prototype.applySavedQuery = function ( queryID
) {
787 var currentMatchingQuery
,
788 params
= this.savedQueriesModel
.getItemParams( queryID
);
790 currentMatchingQuery
= this.findQueryMatchingCurrentState();
793 currentMatchingQuery
&&
794 currentMatchingQuery
.getID() === queryID
796 // If the query we want to load is the one that is already
797 // loaded, don't reload it
801 if ( this.applyParamChange( params
) ) {
802 // Update changes list only if there was a difference in filter selection
803 this.updateChangesList();
805 this.uriProcessor
.updateURL( params
);
808 // Log filter grouping
809 this.trackFilterGroupings( 'savedfilters' );
813 * Check whether the current filter and highlight state exists
814 * in the saved queries model.
816 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
818 Controller
.prototype.findQueryMatchingCurrentState = function () {
819 return this.savedQueriesModel
.findMatchingQuery(
820 this.filtersModel
.getCurrentParameterState( true )
825 * Save the current state of the saved queries model with all
826 * query item representation in the user settings.
828 Controller
.prototype._saveSavedQueries = function () {
829 var stringified
, oldPrefValue
,
830 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
831 state
= this.savedQueriesModel
.getState();
834 stringified
= JSON
.stringify( state
);
836 if ( byteLength( stringified
) > 65535 ) {
837 // Sanity check, since the preference can only hold that.
841 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
842 // The queries were converted from the previous version
843 // Keep the old string in the [prefname]-versionbackup
844 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
846 // Save the old preference in the backup preference
847 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
848 // Update the preference for this session
849 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
852 // Save the preference
853 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
854 // Update the preference for this session
855 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
857 // Tag as already saved so we don't do this again
858 this.wereSavedQueriesSaved
= true;
862 * Update sticky preferences with current model state
864 Controller
.prototype.updateStickyPreferences = function () {
865 // Update default sticky values with selected, whether they came from
866 // the initial defaults or from the URL value that is being normalized
867 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).findSelectedItems()[ 0 ].getParamName() );
868 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).findSelectedItems()[ 0 ].getParamName() );
870 // TODO: Make these automatic by having the model go over sticky
871 // items and update their default values automatically
875 * Update the limit default value
877 * @param {number} newValue New value
879 Controller
.prototype.updateLimitDefault = function ( newValue
) {
880 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
884 * Update the days default value
886 * @param {number} newValue New value
888 Controller
.prototype.updateDaysDefault = function ( newValue
) {
889 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
893 * Update the group by page default value
895 * @param {boolean} newValue New value
897 Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
898 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
902 * Update the collapsed state value
904 * @param {boolean} isCollapsed Filter area is collapsed
906 Controller
.prototype.updateCollapsedState = function ( isCollapsed
) {
907 this.updateNumericPreference( this.collapsedPreferenceName
, Number( isCollapsed
) );
911 * Update a numeric preference with a new value
913 * @param {string} prefName Preference name
914 * @param {number|string} newValue New value
916 Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
917 // FIXME: $.isNumeric is deprecated
918 // eslint-disable-next-line no-jquery/no-is-numeric
919 if ( !$.isNumeric( newValue
) ) {
923 newValue
= Number( newValue
);
925 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
926 // Save the preference
927 new mw
.Api().saveOption( prefName
, newValue
);
928 // Update the preference for this session
929 mw
.user
.options
.set( prefName
, newValue
);
934 * Synchronize the URL with the current state of the filters
935 * without adding an history entry.
937 Controller
.prototype.replaceUrl = function () {
938 this.uriProcessor
.updateURL();
942 * Update filter state (selection and highlighting) based
943 * on current URL values.
945 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
946 * list based on the updated model.
948 Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
949 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
951 this.uriProcessor
.updateModelBasedOnQuery();
953 // Update the sticky preferences, in case we received a value
955 this.updateStickyPreferences();
957 // Only update and fetch new results if it is requested
958 if ( fetchChangesList
) {
959 this.updateChangesList();
964 * Update the list of changes and notify the model
966 * @param {Object} [params] Extra parameters to add to the API call
967 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
968 * @return {jQuery.Promise} Promise that is resolved when the update is complete
970 Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
971 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
973 if ( updateMode
=== this.FILTER_CHANGE
) {
974 this.uriProcessor
.updateURL( params
);
976 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
977 this.changesListModel
.invalidate();
979 this.changesListModel
.setNewChangesExist( false );
980 this.updatingChangesList
= true;
981 return this._fetchChangesList()
984 function ( pieces
) {
985 var $changesListContent
= pieces
.changes
,
986 $fieldset
= pieces
.fieldset
;
987 this.changesListModel
.update(
990 pieces
.noResultsDetails
,
992 // separator between old and new changes
993 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
996 // Do nothing for failure
998 .always( function () {
999 this.updatingChangesList
= false;
1004 * Get an object representing the default parameter state, whether
1005 * it is from the model defaults or from the saved queries.
1007 * @return {Object} Default parameters
1009 Controller
.prototype._getDefaultParams = function () {
1010 if ( this.savedQueriesModel
.getDefault() ) {
1011 return this.savedQueriesModel
.getDefaultParams();
1013 return this.filtersModel
.getDefaultParams();
1018 * Query the list of changes from the server for the current filters
1020 * @param {string} counterId Id for this request. To allow concurrent requests
1021 * not to invalidate each other.
1022 * @param {Object} [params={}] Parameters to add to the query
1024 * @return {jQuery.Promise} Promise object resolved with { content, status }
1026 Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1027 var uri
= this.uriProcessor
.getUpdatedUri(),
1028 stickyParams
= this.filtersModel
.getStickyParamsValues(),
1032 params
= params
|| {};
1033 params
.action
= 'render'; // bypasses MW chrome
1035 uri
.extend( params
);
1037 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1038 requestId
= ++this.requestCounter
[ counterId
];
1039 latestRequest = function () {
1040 return requestId
=== this.requestCounter
[ counterId
];
1043 // Sticky parameters override the URL params
1044 // this is to make sure that whether we represent
1045 // the sticky params in the URL or not (they may
1046 // be normalized out) the sticky parameters are
1047 // always being sent to the server with their
1048 // current/default values
1049 uri
.extend( stickyParams
);
1051 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1053 function ( content
, message
, jqXHR
) {
1054 if ( !latestRequest() ) {
1055 return $.Deferred().reject();
1059 status
: jqXHR
.status
1062 // RC returns 404 when there is no results
1063 function ( jqXHR
) {
1064 if ( latestRequest() ) {
1065 return $.Deferred().resolve(
1067 content
: jqXHR
.responseText
,
1068 status
: jqXHR
.status
1077 * Fetch the list of changes from the server for the current filters
1079 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1082 Controller
.prototype._fetchChangesList = function () {
1083 return this._queryChangesList( 'updateChangesList' )
1088 // Status code 0 is not HTTP status code,
1089 // but is valid value of XMLHttpRequest status.
1090 // It is used for variety of network errors, for example
1091 // when an AJAX call was cancelled before getting the response
1092 if ( data
&& data
.status
=== 0 ) {
1094 changes
: 'NO_RESULTS',
1095 // We need empty result set, to avoid exceptions because of undefined value
1097 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1101 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1102 data
? data
.content
: ''
1105 return this._extractChangesListInfo( $parsed
, data
.status
);
1111 * Track usage of highlight feature
1113 * @param {string} action
1114 * @param {Array|Object|string} filters
1116 Controller
.prototype._trackHighlight = function ( action
, filters
) {
1117 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1118 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1120 'event.ChangesListHighlights',
1124 userId
: mw
.user
.getId()
1130 * Track filter grouping usage
1132 * @param {string} action Action taken
1134 Controller
.prototype.trackFilterGroupings = function ( action
) {
1135 var controller
= this,
1136 rightNow
= new Date().getTime(),
1137 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1138 // Get all current filters
1139 filters
= this.filtersModel
.findSelectedItems().map( function ( item
) {
1140 return item
.getName();
1143 action
= action
|| 'filtermenu';
1145 // Check if these filters were the ones we just logged previously
1146 // (Don't log the same grouping twice, in case the user opens/closes)
1147 // the menu without action, or with the same result
1149 // Only log if the two arrays are different in size
1150 filters
.length
!== this.prevLoggedItems
.length
||
1151 // Or if any filters are not the same as the cached filters
1152 filters
.some( function ( filterName
) {
1153 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1155 // Or if any cached filters are not the same as given filters
1156 this.prevLoggedItems
.some( function ( filterName
) {
1157 return filters
.indexOf( filterName
) === -1;
1160 filters
.forEach( function ( filterName
) {
1162 'event.ChangesListFilterGrouping',
1165 groupIdentifier
: randomIdentifier
,
1167 userId
: mw
.user
.getId()
1172 // Cache the filter names
1173 this.prevLoggedItems
= filters
;
1178 * Apply a change of parameters to the model state, and check whether
1179 * the new state is different than the old state.
1181 * @param {Object} newParamState New parameter state to apply
1182 * @return {boolean} New applied model state is different than the previous state
1184 Controller
.prototype.applyParamChange = function ( newParamState
) {
1186 before
= this.filtersModel
.getSelectedState();
1188 this.filtersModel
.updateStateFromParams( newParamState
);
1190 after
= this.filtersModel
.getSelectedState();
1192 return !OO
.compare( before
, after
);
1196 * Mark all changes as seen on Watchlist
1198 Controller
.prototype.markAllChangesAsSeen = function () {
1199 var api
= new mw
.Api();
1200 api
.postWithToken( 'csrf', {
1202 action
: 'setnotificationtimestamp',
1203 entirewatchlist
: true
1204 } ).then( function () {
1205 this.updateChangesList( null, 'markSeen' );
1210 * Set the current search for the system.
1212 * @param {string} searchQuery Search query, including triggers
1214 Controller
.prototype.setSearch = function ( searchQuery
) {
1215 this.filtersModel
.setSearch( searchQuery
);
1219 * Switch the view by changing the search query trigger
1220 * without changing the search term
1222 * @param {string} view View to change to
1224 Controller
.prototype.switchView = function ( view
) {
1226 this.filtersModel
.getViewTrigger( view
) +
1227 this.filtersModel
.removeViewTriggers( this.filtersModel
.getSearch() )
1232 * Reset the search for a specific view. This means we null the search query
1233 * and replace it with the relevant trigger for the requested view
1235 * @param {string} [view='default'] View to change to
1237 Controller
.prototype.resetSearchForView = function ( view
) {
1238 view
= view
|| 'default';
1241 this.filtersModel
.getViewTrigger( view
)
1245 module
.exports
= Controller
;