2 /* eslint no-underscore-dangle: "off" */
4 * Controller for the filters in Recent Changes
8 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
9 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
10 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
11 * @param {Object} config Additional configuration
12 * @cfg {string} savedQueriesPreferenceName Where to save the saved queries
13 * @cfg {string} daysPreferenceName Preference name for the days filter
14 * @cfg {string} limitPreferenceName Preference name for the limit filter
15 * @cfg {boolean} [normalizeTarget] Dictates whether or not to go through the
16 * title normalization to separate title subpage/parts into the target= url
19 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
, config
) {
20 this.filtersModel
= filtersModel
;
21 this.changesListModel
= changesListModel
;
22 this.savedQueriesModel
= savedQueriesModel
;
23 this.savedQueriesPreferenceName
= config
.savedQueriesPreferenceName
;
24 this.daysPreferenceName
= config
.daysPreferenceName
;
25 this.limitPreferenceName
= config
.limitPreferenceName
;
26 this.normalizeTarget
= !!config
.normalizeTarget
;
28 this.requestCounter
= {};
29 this.baseFilterState
= {};
30 this.uriProcessor
= null;
31 this.initializing
= false;
32 this.wereSavedQueriesSaved
= false;
34 this.prevLoggedItems
= [];
36 this.FILTER_CHANGE
= 'filterChange';
37 this.SHOW_NEW_CHANGES
= 'showNewChanges';
38 this.LIVE_UPDATE
= 'liveUpdate';
42 OO
.initClass( mw
.rcfilters
.Controller
);
45 * Initialize the filter and parameter states
47 * @param {Array} filterStructure Filter definition and structure for the model
48 * @param {Object} [namespaceStructure] Namespace definition
49 * @param {Object} [tagList] Tag definition
50 * @param {Object} [conditionalViews] Conditional view definition
52 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
, conditionalViews
) {
53 var parsedSavedQueries
, pieces
,
54 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
55 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
57 views
= $.extend( true, {}, conditionalViews
),
62 if ( namespaceStructure
) {
64 $.each( namespaceStructure
, function ( namespaceID
, label
) {
65 // Build and clean up the individual namespace items definition
68 label
: label
|| mw
.msg( 'blanknamespace' ),
71 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
74 cssClass
: 'mw-changeslist-ns-' + namespaceID
79 title
: mw
.msg( 'namespaces' ),
82 // Group definition (single group)
83 name
: 'namespace', // parameter name is singular
84 type
: 'string_options',
85 title
: mw
.msg( 'namespaces' ),
86 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
107 title
: mw
.msg( 'rcfilters-view-tags' ),
110 // Group definition (single group)
111 name
: 'tagfilter', // Parameter name
112 type
: 'string_options',
113 title
: 'rcfilters-view-tags', // Message key
114 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
122 // Add parameter range operations
127 type
: 'single_option',
128 title
: '', // Because it's a hidden group, this title actually appears nowhere
130 allowArbitrary
: true,
131 validate
: $.isNumeric
,
133 min
: 0, // The server normalizes negative numbers to 0 results
136 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
137 'default': mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
139 filters
: displayConfig
.limitArray
.map( function ( num
) {
140 return controller
._createFilterDataFromNumber( num
, num
);
145 type
: 'single_option',
146 title
: '', // Because it's a hidden group, this title actually appears nowhere
148 allowArbitrary
: true,
149 validate
: $.isNumeric
,
152 max
: displayConfig
.maxDays
154 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
155 numToLabelFunc: function ( i
) {
156 return Number( i
) < 1 ?
157 ( Number( i
) * 24 ).toFixed( 2 ) :
160 'default': mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
163 // Hours (1, 2, 6, 12)
164 0.04166, 0.0833, 0.25, 0.5
166 ].concat( displayConfig
.daysArray
)
167 .map( function ( num
) {
168 return controller
._createFilterDataFromNumber(
170 // Convert fractions of days to number of hours for the labels
171 num
< 1 ? Math
.round( num
* 24 ) : num
183 title
: '', // Because it's a hidden group, this title actually appears nowhere
189 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
196 // Before we do anything, we need to see if we require additional items in the
197 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
198 // groups; if we ever expand it, this might need further generalization:
199 $.each( views
, function ( viewName
, viewData
) {
200 viewData
.groups
.forEach( function ( groupData
) {
201 var extraValues
= [];
202 if ( groupData
.allowArbitrary
) {
203 // If the value in the URI isn't in the group, add it
204 if ( uri
.query
[ groupData
.name
] !== undefined ) {
205 extraValues
.push( uri
.query
[ groupData
.name
] );
207 // If the default value isn't in the group, add it
208 if ( groupData
.default !== undefined ) {
209 extraValues
.push( String( groupData
.default ) );
211 controller
.addNumberValuesToGroup( groupData
, extraValues
);
216 // Initialize the model
217 this.filtersModel
.initializeFilters( filterStructure
, views
);
219 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
221 { normalizeTarget
: this.normalizeTarget
}
224 if ( !mw
.user
.isAnon() ) {
226 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
228 parsedSavedQueries
= {};
231 // Initialize saved queries
232 this.savedQueriesModel
.initialize( parsedSavedQueries
);
233 if ( this.savedQueriesModel
.isConverted() ) {
234 // Since we know we converted, we're going to re-save
235 // the queries so they are now migrated to the new format
236 this._saveSavedQueries();
240 // Check whether we need to load defaults.
241 // We do this by checking whether the current URI query
242 // contains any parameters recognized by the system.
243 // If it does, we load the given state.
244 // If it doesn't, we have no values at all, and we assume
245 // the user loads the base-page and we load defaults.
246 // Defaults should only be applied on load (if necessary)
248 this.initializing
= true;
250 if ( defaultSavedQueryExists
) {
251 // This came from the server, meaning that we have a default
252 // saved query, but the server could not load it, probably because
253 // it was pre-conversion to the new format.
254 // We need to load this query again
255 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
257 // There are either recognized parameters in the URL
258 // or there are none, but there is also no default
259 // saved query (so defaults are from the backend)
260 // We want to update the state but not fetch results
262 this.updateStateFromUrl( false );
264 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
266 // Update the changes list with the existing data
267 // so it gets processed
268 this.changesListModel
.update(
271 pieces
.noResultsDetails
,
272 true // We're using existing DOM elements
276 this.initializing
= false;
277 this.switchView( 'default' );
279 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
280 if ( this.pollingRate
) {
281 this._scheduleLiveUpdate();
286 * Extracts information from the changes list DOM
288 * @param {jQuery} $root Root DOM to find children from
289 * @param {boolean} [statusCode] Server response status code
290 * @return {Object} Information about changes list
291 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
292 * (either normally or as an error)
293 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
294 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
295 * @return {jQuery} return.fieldset Fieldset
297 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
, statusCode
) {
299 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
300 areResults
= !!$changesListContents
.length
,
301 checkForLogout
= !areResults
&& statusCode
=== 200;
303 // We check if user logged out on different tab/browser or the session has expired.
304 // 205 status code returned from the server, which indicates that we need to reload the page
305 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
306 // status code (if everything else goes well).
308 if ( checkForLogout
&& !!$root
.find( '#wpName1' ).length
) {
309 location
.reload( false );
314 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
315 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
319 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
320 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
321 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
322 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
324 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
332 * Create filter data from a number, for the filters that are numerical value
334 * @param {Number} num Number
335 * @param {Number} numForDisplay Number for the label
336 * @return {Object} Filter data
338 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
341 label
: mw
.language
.convertNumber( numForDisplay
)
346 * Add an arbitrary values to groups that allow arbitrary values
348 * @param {Object} groupData Group data
349 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
351 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
352 var controller
= this,
353 normalizeWithinRange = function ( range
, val
) {
354 if ( val
< range
.min
) {
355 return range
.min
; // Min
356 } else if ( val
>= range
.max
) {
357 return range
.max
; // Max
362 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
364 // Normalize the arbitrary values and the default value for a range
365 if ( groupData
.range
) {
366 arbitraryValues
= arbitraryValues
.map( function ( val
) {
367 return normalizeWithinRange( groupData
.range
, val
);
370 // Normalize the default, since that's user defined
371 if ( groupData
.default !== undefined ) {
372 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
376 // This is only true for single_option group
377 // We assume these are the only groups that will allow for
378 // arbitrary, since it doesn't make any sense for the other
380 arbitraryValues
.forEach( function ( val
) {
382 // If the group allows for arbitrary data
383 groupData
.allowArbitrary
&&
384 // and it is single_option (or string_options, but we
385 // don't have cases of those yet, nor do we plan to)
386 groupData
.type
=== 'single_option' &&
387 // and, if there is a validate method and it passes on
389 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
390 // but if that value isn't already in the definition
392 .map( function ( filterData
) {
393 return String( filterData
.name
);
395 .indexOf( String( val
) ) === -1
397 // Add the filter information
398 groupData
.filters
.push( controller
._createFilterDataFromNumber(
400 groupData
.numToLabelFunc
?
401 groupData
.numToLabelFunc( val
) :
405 // If there's a sort function set up, re-sort the values
406 if ( groupData
.sortFunc
) {
407 groupData
.filters
.sort( groupData
.sortFunc
);
414 * Reset to default filters
416 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
417 var params
= this._getDefaultParams();
418 if ( this.applyParamChange( params
) ) {
419 // Only update the changes list if there was a change to actual filters
420 this.updateChangesList();
422 this.uriProcessor
.updateURL( params
);
427 * Check whether the default values of the filters are all false.
429 * @return {boolean} Defaults are all false
431 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
432 return $.isEmptyObject( this._getDefaultParams() );
436 * Empty all selected filters
438 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
439 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
440 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
442 if ( this.applyParamChange( {} ) ) {
443 // Only update the changes list if there was a change to actual filters
444 this.updateChangesList();
446 this.uriProcessor
.updateURL();
449 if ( highlightedFilterNames
) {
450 this._trackHighlight( 'clearAll', highlightedFilterNames
);
455 * Update the selected state of a filter
457 * @param {string} filterName Filter name
458 * @param {boolean} [isSelected] Filter selected state
460 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
461 var filterItem
= this.filtersModel
.getItemByName( filterName
);
464 // If no filter was found, break
468 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
470 if ( filterItem
.isSelected() !== isSelected
) {
471 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
473 this.updateChangesList();
475 // Check filter interactions
476 this.filtersModel
.reassessFilterInteractions( filterItem
);
481 * Clear both highlight and selection of a filter
483 * @param {string} filterName Name of the filter item
485 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
486 var filterItem
= this.filtersModel
.getItemByName( filterName
),
487 isHighlighted
= filterItem
.isHighlighted(),
488 isSelected
= filterItem
.isSelected();
490 if ( isSelected
|| isHighlighted
) {
491 this.filtersModel
.clearHighlightColor( filterName
);
492 this.filtersModel
.toggleFilterSelected( filterName
, false );
495 // Only update the changes list if the filter changed
496 // its selection state. If it only changed its highlight
498 this.updateChangesList();
501 this.filtersModel
.reassessFilterInteractions( filterItem
);
503 // Log filter grouping
504 this.trackFilterGroupings( 'removefilter' );
507 if ( isHighlighted
) {
508 this._trackHighlight( 'clear', filterName
);
513 * Toggle the highlight feature on and off
515 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
516 this.filtersModel
.toggleHighlight();
517 this.uriProcessor
.updateURL();
519 if ( this.filtersModel
.isHighlightEnabled() ) {
520 mw
.hook( 'RcFilters.highlight.enable' ).fire();
525 * Toggle the namespaces inverted feature on and off
527 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
528 this.filtersModel
.toggleInvertedNamespaces();
530 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
531 function ( filterItem
) { return filterItem
.isSelected(); }
534 // Only re-fetch results if there are namespace items that are actually selected
535 this.updateChangesList();
537 this.uriProcessor
.updateURL();
542 * Set the value of the 'showlinkedto' parameter
543 * @param {boolean} value
545 mw
.rcfilters
.Controller
.prototype.setShowLinkedTo = function ( value
) {
546 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
547 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
549 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
550 this.uriProcessor
.updateURL();
551 // reload the results only when target is set
552 if ( targetItem
.getValue() ) {
553 this.updateChangesList();
558 * Set the target page
559 * @param {string} page
561 mw
.rcfilters
.Controller
.prototype.setTargetPage = function ( page
) {
562 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
563 targetItem
.setValue( page
);
564 this.uriProcessor
.updateURL();
565 this.updateChangesList();
569 * Set the highlight color for a filter item
571 * @param {string} filterName Name of the filter item
572 * @param {string} color Selected color
574 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
575 this.filtersModel
.setHighlightColor( filterName
, color
);
576 this.uriProcessor
.updateURL();
577 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
581 * Clear highlight for a filter item
583 * @param {string} filterName Name of the filter item
585 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
586 this.filtersModel
.clearHighlightColor( filterName
);
587 this.uriProcessor
.updateURL();
588 this._trackHighlight( 'clear', filterName
);
592 * Enable or disable live updates.
593 * @param {boolean} enable True to enable, false to disable
595 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
596 this.changesListModel
.toggleLiveUpdate( enable
);
597 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
598 this.updateChangesList( null, this.LIVE_UPDATE
);
603 * Set a timeout for the next live update.
606 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
607 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
611 * Perform a live update.
614 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
615 if ( !this._shouldCheckForNewChanges() ) {
616 // skip this turn and check back later
617 this._scheduleLiveUpdate();
621 this._checkForNewChanges()
622 .then( function ( statusCode
) {
623 // no result is 204 with the 'peek' param
625 var newChanges
= statusCode
=== 200;
627 if ( !this._shouldCheckForNewChanges() ) {
628 // by the time the response is received,
629 // it may not be appropriate anymore
633 // 205 is the status code returned from server when user's logged in/out
634 // status is not matching while fetching live update changes.
635 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
637 if ( statusCode
=== 205 ) {
638 location
.reload( false );
643 if ( this.changesListModel
.getLiveUpdate() ) {
644 return this.updateChangesList( null, this.LIVE_UPDATE
);
646 this.changesListModel
.setNewChangesExist( true );
650 .always( this._scheduleLiveUpdate
.bind( this ) );
654 * @return {boolean} It's appropriate to check for new changes now
657 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
658 return !document
.hidden
&&
659 !this.filtersModel
.hasConflict() &&
660 !this.changesListModel
.getNewChangesExist() &&
661 !this.updatingChangesList
&&
662 this.changesListModel
.getNextFrom();
666 * Check if new changes, newer than those currently shown, are available
668 * @return {jQuery.Promise} Promise object that resolves with a bool
669 * specifying if there are new changes or not
673 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
676 peek
: 1, // bypasses ChangesList specific UI
677 from: this.changesListModel
.getNextFrom(),
678 isAnon
: mw
.user
.isAnon()
680 return this._queryChangesList( 'liveUpdate', params
).then(
688 * Show the new changes
690 * @return {jQuery.Promise} Promise object that resolves after
691 * fetching and showing the new changes
693 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
694 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
698 * Save the current model state as a saved query
700 * @param {string} [label] Label of the saved query
701 * @param {boolean} [setAsDefault=false] This query should be set as the default
703 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
705 this.savedQueriesModel
.addNewQuery(
706 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
707 this.filtersModel
.getCurrentParameterState( true ),
712 this._saveSavedQueries();
716 * Remove a saved query
718 * @param {string} queryID Query id
720 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
721 this.savedQueriesModel
.removeQuery( queryID
);
723 this._saveSavedQueries();
727 * Rename a saved query
729 * @param {string} queryID Query id
730 * @param {string} newLabel New label for the query
732 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
733 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
736 queryItem
.updateLabel( newLabel
);
738 this._saveSavedQueries();
742 * Set a saved query as default
744 * @param {string} queryID Query Id. If null is given, default
747 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
748 this.savedQueriesModel
.setDefault( queryID
);
749 this._saveSavedQueries();
755 * @param {string} queryID Query id
757 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
758 var currentMatchingQuery
,
759 params
= this.savedQueriesModel
.getItemParams( queryID
);
761 currentMatchingQuery
= this.findQueryMatchingCurrentState();
764 currentMatchingQuery
&&
765 currentMatchingQuery
.getID() === queryID
767 // If the query we want to load is the one that is already
768 // loaded, don't reload it
772 if ( this.applyParamChange( params
) ) {
773 // Update changes list only if there was a difference in filter selection
774 this.updateChangesList();
776 this.uriProcessor
.updateURL( params
);
779 // Log filter grouping
780 this.trackFilterGroupings( 'savedfilters' );
784 * Check whether the current filter and highlight state exists
785 * in the saved queries model.
787 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
789 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
790 return this.savedQueriesModel
.findMatchingQuery(
791 this.filtersModel
.getCurrentParameterState( true )
796 * Save the current state of the saved queries model with all
797 * query item representation in the user settings.
799 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
800 var stringified
, oldPrefValue
,
801 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
802 state
= this.savedQueriesModel
.getState();
805 stringified
= JSON
.stringify( state
);
807 if ( $.byteLength( stringified
) > 65535 ) {
808 // Sanity check, since the preference can only hold that.
812 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
813 // The queries were converted from the previous version
814 // Keep the old string in the [prefname]-versionbackup
815 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
817 // Save the old preference in the backup preference
818 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
819 // Update the preference for this session
820 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
823 // Save the preference
824 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
825 // Update the preference for this session
826 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
828 // Tag as already saved so we don't do this again
829 this.wereSavedQueriesSaved
= true;
833 * Update sticky preferences with current model state
835 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
836 // Update default sticky values with selected, whether they came from
837 // the initial defaults or from the URL value that is being normalized
838 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
839 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
841 // TODO: Make these automatic by having the model go over sticky
842 // items and update their default values automatically
846 * Update the limit default value
848 * @param {number} newValue New value
850 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
851 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
855 * Update the days default value
857 * @param {number} newValue New value
859 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
860 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
864 * Update the group by page default value
866 * @param {boolean} newValue New value
868 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
869 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
873 * Update a numeric preference with a new value
875 * @param {string} prefName Preference name
876 * @param {number|string} newValue New value
878 mw
.rcfilters
.Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
879 if ( !$.isNumeric( newValue
) ) {
883 newValue
= Number( newValue
);
885 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
886 // Save the preference
887 new mw
.Api().saveOption( prefName
, newValue
);
888 // Update the preference for this session
889 mw
.user
.options
.set( prefName
, newValue
);
894 * Synchronize the URL with the current state of the filters
895 * without adding an history entry.
897 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
898 this.uriProcessor
.updateURL();
902 * Update filter state (selection and highlighting) based
903 * on current URL values.
905 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
906 * list based on the updated model.
908 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
909 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
911 this.uriProcessor
.updateModelBasedOnQuery();
913 // Update the sticky preferences, in case we received a value
915 this.updateStickyPreferences();
917 // Only update and fetch new results if it is requested
918 if ( fetchChangesList
) {
919 this.updateChangesList();
924 * Update the list of changes and notify the model
926 * @param {Object} [params] Extra parameters to add to the API call
927 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
928 * @return {jQuery.Promise} Promise that is resolved when the update is complete
930 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
931 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
933 if ( updateMode
=== this.FILTER_CHANGE
) {
934 this.uriProcessor
.updateURL( params
);
936 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
937 this.changesListModel
.invalidate();
939 this.changesListModel
.setNewChangesExist( false );
940 this.updatingChangesList
= true;
941 return this._fetchChangesList()
944 function ( pieces
) {
945 var $changesListContent
= pieces
.changes
,
946 $fieldset
= pieces
.fieldset
;
947 this.changesListModel
.update(
950 pieces
.noResultsDetails
,
952 // separator between old and new changes
953 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
956 // Do nothing for failure
958 .always( function () {
959 this.updatingChangesList
= false;
964 * Get an object representing the default parameter state, whether
965 * it is from the model defaults or from the saved queries.
967 * @return {Object} Default parameters
969 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
970 if ( this.savedQueriesModel
.getDefault() ) {
971 return this.savedQueriesModel
.getDefaultParams();
973 return this.filtersModel
.getDefaultParams();
978 * Query the list of changes from the server for the current filters
980 * @param {string} counterId Id for this request. To allow concurrent requests
981 * not to invalidate each other.
982 * @param {Object} [params={}] Parameters to add to the query
984 * @return {jQuery.Promise} Promise object resolved with { content, status }
986 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
987 var uri
= this.uriProcessor
.getUpdatedUri(),
988 stickyParams
= this.filtersModel
.getStickyParamsValues(),
992 params
= params
|| {};
993 params
.action
= 'render'; // bypasses MW chrome
995 uri
.extend( params
);
997 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
998 requestId
= ++this.requestCounter
[ counterId
];
999 latestRequest = function () {
1000 return requestId
=== this.requestCounter
[ counterId
];
1003 // Sticky parameters override the URL params
1004 // this is to make sure that whether we represent
1005 // the sticky params in the URL or not (they may
1006 // be normalized out) the sticky parameters are
1007 // always being sent to the server with their
1008 // current/default values
1009 uri
.extend( stickyParams
);
1011 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1013 function ( content
, message
, jqXHR
) {
1014 if ( !latestRequest() ) {
1015 return $.Deferred().reject();
1019 status
: jqXHR
.status
1022 // RC returns 404 when there is no results
1023 function ( jqXHR
) {
1024 if ( latestRequest() ) {
1025 return $.Deferred().resolve(
1027 content
: jqXHR
.responseText
,
1028 status
: jqXHR
.status
1037 * Fetch the list of changes from the server for the current filters
1039 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1042 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1043 return this._queryChangesList( 'updateChangesList' )
1048 // Status code 0 is not HTTP status code,
1049 // but is valid value of XMLHttpRequest status.
1050 // It is used for variety of network errors, for example
1051 // when an AJAX call was cancelled before getting the response
1052 if ( data
&& data
.status
=== 0 ) {
1054 changes
: 'NO_RESULTS',
1055 // We need empty result set, to avoid exceptions because of undefined value
1057 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1061 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1062 data
? data
.content
: ''
1065 return this._extractChangesListInfo( $parsed
, data
.status
);
1071 * Track usage of highlight feature
1073 * @param {string} action
1074 * @param {Array|Object|string} filters
1076 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1077 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1078 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1080 'event.ChangesListHighlights',
1084 userId
: mw
.user
.getId()
1090 * Track filter grouping usage
1092 * @param {string} action Action taken
1094 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1095 var controller
= this,
1096 rightNow
= new Date().getTime(),
1097 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1098 // Get all current filters
1099 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1100 return item
.getName();
1103 action
= action
|| 'filtermenu';
1105 // Check if these filters were the ones we just logged previously
1106 // (Don't log the same grouping twice, in case the user opens/closes)
1107 // the menu without action, or with the same result
1109 // Only log if the two arrays are different in size
1110 filters
.length
!== this.prevLoggedItems
.length
||
1111 // Or if any filters are not the same as the cached filters
1112 filters
.some( function ( filterName
) {
1113 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1115 // Or if any cached filters are not the same as given filters
1116 this.prevLoggedItems
.some( function ( filterName
) {
1117 return filters
.indexOf( filterName
) === -1;
1120 filters
.forEach( function ( filterName
) {
1122 'event.ChangesListFilterGrouping',
1125 groupIdentifier
: randomIdentifier
,
1127 userId
: mw
.user
.getId()
1132 // Cache the filter names
1133 this.prevLoggedItems
= filters
;
1138 * Apply a change of parameters to the model state, and check whether
1139 * the new state is different than the old state.
1141 * @param {Object} newParamState New parameter state to apply
1142 * @return {boolean} New applied model state is different than the previous state
1144 mw
.rcfilters
.Controller
.prototype.applyParamChange = function ( newParamState
) {
1146 before
= this.filtersModel
.getSelectedState();
1148 this.filtersModel
.updateStateFromParams( newParamState
);
1150 after
= this.filtersModel
.getSelectedState();
1152 return !OO
.compare( before
, after
);
1156 * Mark all changes as seen on Watchlist
1158 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1159 var api
= new mw
.Api();
1160 api
.postWithToken( 'csrf', {
1162 action
: 'setnotificationtimestamp',
1163 entirewatchlist
: true
1164 } ).then( function () {
1165 this.updateChangesList( null, 'markSeen' );
1170 * Set the current search for the system.
1172 * @param {string} searchQuery Search query, including triggers
1174 mw
.rcfilters
.Controller
.prototype.setSearch = function ( searchQuery
) {
1175 this.filtersModel
.setSearch( searchQuery
);
1179 * Switch the view by changing the search query trigger
1180 * without changing the search term
1182 * @param {string} view View to change to
1184 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
1186 this.filtersModel
.getViewTrigger( view
) +
1187 this.filtersModel
.removeViewTriggers( this.filtersModel
.getSearch() )
1192 * Reset the search for a specific view. This means we null the search query
1193 * and replace it with the relevant trigger for the requested view
1195 * @param {string} [view='default'] View to change to
1197 mw
.rcfilters
.Controller
.prototype.resetSearchForView = function ( view
) {
1198 view
= view
|| 'default';
1201 this.filtersModel
.getViewTrigger( view
)
1204 }( mediaWiki
, jQuery
) );