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
16 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
, config
) {
17 this.filtersModel
= filtersModel
;
18 this.changesListModel
= changesListModel
;
19 this.savedQueriesModel
= savedQueriesModel
;
20 this.savedQueriesPreferenceName
= config
.savedQueriesPreferenceName
;
21 this.daysPreferenceName
= config
.daysPreferenceName
;
22 this.limitPreferenceName
= config
.limitPreferenceName
;
24 this.requestCounter
= {};
25 this.baseFilterState
= {};
26 this.uriProcessor
= null;
27 this.initializing
= false;
28 this.wereSavedQueriesSaved
= false;
30 this.prevLoggedItems
= [];
32 this.FILTER_CHANGE
= 'filterChange';
33 this.SHOW_NEW_CHANGES
= 'showNewChanges';
34 this.LIVE_UPDATE
= 'liveUpdate';
38 OO
.initClass( mw
.rcfilters
.Controller
);
41 * Initialize the filter and parameter states
43 * @param {Array} filterStructure Filter definition and structure for the model
44 * @param {Object} [namespaceStructure] Namespace definition
45 * @param {Object} [tagList] Tag definition
47 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
48 var parsedSavedQueries
, pieces
,
49 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
50 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
57 if ( namespaceStructure
) {
59 $.each( namespaceStructure
, function ( namespaceID
, label
) {
60 // Build and clean up the individual namespace items definition
63 label
: label
|| mw
.msg( 'blanknamespace' ),
66 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
69 cssClass
: 'mw-changeslist-ns-' + namespaceID
74 title
: mw
.msg( 'namespaces' ),
77 // Group definition (single group)
78 name
: 'namespace', // parameter name is singular
79 type
: 'string_options',
80 title
: mw
.msg( 'namespaces' ),
81 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
102 title
: mw
.msg( 'rcfilters-view-tags' ),
105 // Group definition (single group)
106 name
: 'tagfilter', // Parameter name
107 type
: 'string_options',
108 title
: 'rcfilters-view-tags', // Message key
109 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
117 // Add parameter range operations
122 type
: 'single_option',
123 title
: '', // Because it's a hidden group, this title actually appears nowhere
125 allowArbitrary
: true,
126 validate
: $.isNumeric
,
128 min
: 0, // The server normalizes negative numbers to 0 results
131 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
132 'default': mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
134 filters
: displayConfig
.limitArray
.map( function ( num
) {
135 return controller
._createFilterDataFromNumber( num
, num
);
140 type
: 'single_option',
141 title
: '', // Because it's a hidden group, this title actually appears nowhere
143 allowArbitrary
: true,
144 validate
: $.isNumeric
,
147 max
: displayConfig
.maxDays
149 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
150 numToLabelFunc: function ( i
) {
151 return Number( i
) < 1 ?
152 ( Number( i
) * 24 ).toFixed( 2 ) :
155 'default': mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
158 // Hours (1, 2, 6, 12)
159 0.04166, 0.0833, 0.25, 0.5
161 ].concat( displayConfig
.daysArray
)
162 .map( function ( num
) {
163 return controller
._createFilterDataFromNumber(
165 // Convert fractions of days to number of hours for the labels
166 num
< 1 ? Math
.round( num
* 24 ) : num
178 title
: '', // Because it's a hidden group, this title actually appears nowhere
184 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
191 views
.recentChangesLinked
= {
214 name
: 'showlinkedto',
222 // Before we do anything, we need to see if we require additional items in the
223 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
224 // groups; if we ever expand it, this might need further generalization:
225 $.each( views
, function ( viewName
, viewData
) {
226 viewData
.groups
.forEach( function ( groupData
) {
227 var extraValues
= [];
228 if ( groupData
.allowArbitrary
) {
229 // If the value in the URI isn't in the group, add it
230 if ( uri
.query
[ groupData
.name
] !== undefined ) {
231 extraValues
.push( uri
.query
[ groupData
.name
] );
233 // If the default value isn't in the group, add it
234 if ( groupData
.default !== undefined ) {
235 extraValues
.push( String( groupData
.default ) );
237 controller
.addNumberValuesToGroup( groupData
, extraValues
);
242 // Initialize the model
243 this.filtersModel
.initializeFilters( filterStructure
, views
);
245 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
249 if ( !mw
.user
.isAnon() ) {
251 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
253 parsedSavedQueries
= {};
256 // Initialize saved queries
257 this.savedQueriesModel
.initialize( parsedSavedQueries
);
258 if ( this.savedQueriesModel
.isConverted() ) {
259 // Since we know we converted, we're going to re-save
260 // the queries so they are now migrated to the new format
261 this._saveSavedQueries();
265 // Check whether we need to load defaults.
266 // We do this by checking whether the current URI query
267 // contains any parameters recognized by the system.
268 // If it does, we load the given state.
269 // If it doesn't, we have no values at all, and we assume
270 // the user loads the base-page and we load defaults.
271 // Defaults should only be applied on load (if necessary)
273 this.initializing
= true;
275 if ( defaultSavedQueryExists
) {
276 // This came from the server, meaning that we have a default
277 // saved query, but the server could not load it, probably because
278 // it was pre-conversion to the new format.
279 // We need to load this query again
280 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
282 // There are either recognized parameters in the URL
283 // or there are none, but there is also no default
284 // saved query (so defaults are from the backend)
285 // We want to update the state but not fetch results
287 this.updateStateFromUrl( false );
289 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
291 // Update the changes list with the existing data
292 // so it gets processed
293 this.changesListModel
.update(
296 pieces
.noResultsDetails
,
297 true // We're using existing DOM elements
301 this.initializing
= false;
302 this.switchView( 'default' );
304 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
305 if ( this.pollingRate
) {
306 this._scheduleLiveUpdate();
311 * Extracts information from the changes list DOM
313 * @param {jQuery} $root Root DOM to find children from
314 * @return {Object} Information about changes list
315 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
316 * (either normally or as an error)
317 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
318 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
319 * @return {jQuery} return.fieldset Fieldset
321 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
) {
323 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
324 areResults
= !!$changesListContents
.length
;
327 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
328 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
332 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
333 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
334 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
335 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
337 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
345 * Create filter data from a number, for the filters that are numerical value
347 * @param {Number} num Number
348 * @param {Number} numForDisplay Number for the label
349 * @return {Object} Filter data
351 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
354 label
: mw
.language
.convertNumber( numForDisplay
)
359 * Add an arbitrary values to groups that allow arbitrary values
361 * @param {Object} groupData Group data
362 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
364 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
365 var controller
= this,
366 normalizeWithinRange = function ( range
, val
) {
367 if ( val
< range
.min
) {
368 return range
.min
; // Min
369 } else if ( val
>= range
.max
) {
370 return range
.max
; // Max
375 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
377 // Normalize the arbitrary values and the default value for a range
378 if ( groupData
.range
) {
379 arbitraryValues
= arbitraryValues
.map( function ( val
) {
380 return normalizeWithinRange( groupData
.range
, val
);
383 // Normalize the default, since that's user defined
384 if ( groupData
.default !== undefined ) {
385 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
389 // This is only true for single_option group
390 // We assume these are the only groups that will allow for
391 // arbitrary, since it doesn't make any sense for the other
393 arbitraryValues
.forEach( function ( val
) {
395 // If the group allows for arbitrary data
396 groupData
.allowArbitrary
&&
397 // and it is single_option (or string_options, but we
398 // don't have cases of those yet, nor do we plan to)
399 groupData
.type
=== 'single_option' &&
400 // and, if there is a validate method and it passes on
402 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
403 // but if that value isn't already in the definition
405 .map( function ( filterData
) {
406 return String( filterData
.name
);
408 .indexOf( String( val
) ) === -1
410 // Add the filter information
411 groupData
.filters
.push( controller
._createFilterDataFromNumber(
413 groupData
.numToLabelFunc
?
414 groupData
.numToLabelFunc( val
) :
418 // If there's a sort function set up, re-sort the values
419 if ( groupData
.sortFunc
) {
420 groupData
.filters
.sort( groupData
.sortFunc
);
427 * Switch the view of the filters model
429 * @param {string} view Requested view
431 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
432 this.filtersModel
.switchView( view
);
436 * Reset to default filters
438 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
439 var params
= this._getDefaultParams();
440 if ( this.applyParamChange( params
) ) {
441 // Only update the changes list if there was a change to actual filters
442 this.updateChangesList();
444 this.uriProcessor
.updateURL( params
);
449 * Check whether the default values of the filters are all false.
451 * @return {boolean} Defaults are all false
453 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
454 return $.isEmptyObject( this._getDefaultParams() );
458 * Empty all selected filters
460 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
461 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
462 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
464 if ( this.applyParamChange( {} ) ) {
465 // Only update the changes list if there was a change to actual filters
466 this.updateChangesList();
468 this.uriProcessor
.updateURL();
471 if ( highlightedFilterNames
) {
472 this._trackHighlight( 'clearAll', highlightedFilterNames
);
477 * Update the selected state of a filter
479 * @param {string} filterName Filter name
480 * @param {boolean} [isSelected] Filter selected state
482 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
483 var filterItem
= this.filtersModel
.getItemByName( filterName
);
486 // If no filter was found, break
490 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
492 if ( filterItem
.isSelected() !== isSelected
) {
493 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
495 this.updateChangesList();
497 // Check filter interactions
498 this.filtersModel
.reassessFilterInteractions( filterItem
);
503 * Clear both highlight and selection of a filter
505 * @param {string} filterName Name of the filter item
507 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
508 var filterItem
= this.filtersModel
.getItemByName( filterName
),
509 isHighlighted
= filterItem
.isHighlighted(),
510 isSelected
= filterItem
.isSelected();
512 if ( isSelected
|| isHighlighted
) {
513 this.filtersModel
.clearHighlightColor( filterName
);
514 this.filtersModel
.toggleFilterSelected( filterName
, false );
517 // Only update the changes list if the filter changed
518 // its selection state. If it only changed its highlight
520 this.updateChangesList();
523 this.filtersModel
.reassessFilterInteractions( filterItem
);
525 // Log filter grouping
526 this.trackFilterGroupings( 'removefilter' );
529 if ( isHighlighted
) {
530 this._trackHighlight( 'clear', filterName
);
535 * Toggle the highlight feature on and off
537 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
538 this.filtersModel
.toggleHighlight();
539 this.uriProcessor
.updateURL();
541 if ( this.filtersModel
.isHighlightEnabled() ) {
542 mw
.hook( 'RcFilters.highlight.enable' ).fire();
547 * Toggle the namespaces inverted feature on and off
549 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
550 this.filtersModel
.toggleInvertedNamespaces();
552 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
553 function ( filterItem
) { return filterItem
.isSelected(); }
556 // Only re-fetch results if there are namespace items that are actually selected
557 this.updateChangesList();
559 this.uriProcessor
.updateURL();
564 * Set the value of the 'showlinkedto' parameter
565 * @param {boolean} value
567 mw
.rcfilters
.Controller
.prototype.setShowLinkedTo = function ( value
) {
568 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
569 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
571 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
572 this.uriProcessor
.updateURL();
573 // reload the results only when target is set
574 if ( targetItem
.getValue() ) {
575 this.updateChangesList();
580 * Set the target page
581 * @param {string} page
583 mw
.rcfilters
.Controller
.prototype.setTargetPage = function ( page
) {
584 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
585 targetItem
.setValue( page
);
586 this.uriProcessor
.updateURL();
587 this.updateChangesList();
591 * Set the highlight color for a filter item
593 * @param {string} filterName Name of the filter item
594 * @param {string} color Selected color
596 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
597 this.filtersModel
.setHighlightColor( filterName
, color
);
598 this.uriProcessor
.updateURL();
599 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
603 * Clear highlight for a filter item
605 * @param {string} filterName Name of the filter item
607 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
608 this.filtersModel
.clearHighlightColor( filterName
);
609 this.uriProcessor
.updateURL();
610 this._trackHighlight( 'clear', filterName
);
614 * Enable or disable live updates.
615 * @param {boolean} enable True to enable, false to disable
617 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
618 this.changesListModel
.toggleLiveUpdate( enable
);
619 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
620 this.updateChangesList( null, this.LIVE_UPDATE
);
625 * Set a timeout for the next live update.
628 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
629 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
633 * Perform a live update.
636 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
637 if ( !this._shouldCheckForNewChanges() ) {
638 // skip this turn and check back later
639 this._scheduleLiveUpdate();
643 this._checkForNewChanges()
644 .then( function ( newChanges
) {
645 if ( !this._shouldCheckForNewChanges() ) {
646 // by the time the response is received,
647 // it may not be appropriate anymore
652 if ( this.changesListModel
.getLiveUpdate() ) {
653 return this.updateChangesList( null, this.LIVE_UPDATE
);
655 this.changesListModel
.setNewChangesExist( true );
659 .always( this._scheduleLiveUpdate
.bind( this ) );
663 * @return {boolean} It's appropriate to check for new changes now
666 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
667 return !document
.hidden
&&
668 !this.filtersModel
.hasConflict() &&
669 !this.changesListModel
.getNewChangesExist() &&
670 !this.updatingChangesList
&&
671 this.changesListModel
.getNextFrom();
675 * Check if new changes, newer than those currently shown, are available
677 * @return {jQuery.Promise} Promise object that resolves with a bool
678 * specifying if there are new changes or not
682 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
685 peek
: 1, // bypasses ChangesList specific UI
686 from: this.changesListModel
.getNextFrom()
688 return this._queryChangesList( 'liveUpdate', params
).then(
690 // no result is 204 with the 'peek' param
691 return data
.status
=== 200;
697 * Show the new changes
699 * @return {jQuery.Promise} Promise object that resolves after
700 * fetching and showing the new changes
702 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
703 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
707 * Save the current model state as a saved query
709 * @param {string} [label] Label of the saved query
710 * @param {boolean} [setAsDefault=false] This query should be set as the default
712 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
714 this.savedQueriesModel
.addNewQuery(
715 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
716 this.filtersModel
.getCurrentParameterState( true ),
721 this._saveSavedQueries();
725 * Remove a saved query
727 * @param {string} queryID Query id
729 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
730 this.savedQueriesModel
.removeQuery( queryID
);
732 this._saveSavedQueries();
736 * Rename a saved query
738 * @param {string} queryID Query id
739 * @param {string} newLabel New label for the query
741 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
742 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
745 queryItem
.updateLabel( newLabel
);
747 this._saveSavedQueries();
751 * Set a saved query as default
753 * @param {string} queryID Query Id. If null is given, default
756 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
757 this.savedQueriesModel
.setDefault( queryID
);
758 this._saveSavedQueries();
764 * @param {string} queryID Query id
766 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
767 var currentMatchingQuery
,
768 params
= this.savedQueriesModel
.getItemParams( queryID
);
770 currentMatchingQuery
= this.findQueryMatchingCurrentState();
773 currentMatchingQuery
&&
774 currentMatchingQuery
.getID() === queryID
776 // If the query we want to load is the one that is already
777 // loaded, don't reload it
781 if ( this.applyParamChange( params
) ) {
782 // Update changes list only if there was a difference in filter selection
783 this.updateChangesList();
785 this.uriProcessor
.updateURL( params
);
788 // Log filter grouping
789 this.trackFilterGroupings( 'savedfilters' );
793 * Check whether the current filter and highlight state exists
794 * in the saved queries model.
796 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
798 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
799 return this.savedQueriesModel
.findMatchingQuery(
800 this.filtersModel
.getCurrentParameterState( true )
805 * Save the current state of the saved queries model with all
806 * query item representation in the user settings.
808 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
809 var stringified
, oldPrefValue
,
810 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
811 state
= this.savedQueriesModel
.getState();
814 stringified
= JSON
.stringify( state
);
816 if ( $.byteLength( stringified
) > 65535 ) {
817 // Sanity check, since the preference can only hold that.
821 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
822 // The queries were converted from the previous version
823 // Keep the old string in the [prefname]-versionbackup
824 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
826 // Save the old preference in the backup preference
827 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
828 // Update the preference for this session
829 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
832 // Save the preference
833 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
834 // Update the preference for this session
835 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
837 // Tag as already saved so we don't do this again
838 this.wereSavedQueriesSaved
= true;
842 * Update sticky preferences with current model state
844 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
845 // Update default sticky values with selected, whether they came from
846 // the initial defaults or from the URL value that is being normalized
847 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
848 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
850 // TODO: Make these automatic by having the model go over sticky
851 // items and update their default values automatically
855 * Update the limit default value
857 * @param {number} newValue New value
859 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
860 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
864 * Update the days default value
866 * @param {number} newValue New value
868 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
869 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
873 * Update the group by page default value
875 * @param {boolean} newValue New value
877 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
878 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
882 * Update a numeric preference with a new value
884 * @param {string} prefName Preference name
885 * @param {number|string} newValue New value
887 mw
.rcfilters
.Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
888 if ( !$.isNumeric( newValue
) ) {
892 newValue
= Number( newValue
);
894 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
895 // Save the preference
896 new mw
.Api().saveOption( prefName
, newValue
);
897 // Update the preference for this session
898 mw
.user
.options
.set( prefName
, newValue
);
903 * Synchronize the URL with the current state of the filters
904 * without adding an history entry.
906 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
907 this.uriProcessor
.updateURL();
911 * Update filter state (selection and highlighting) based
912 * on current URL values.
914 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
915 * list based on the updated model.
917 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
918 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
920 this.uriProcessor
.updateModelBasedOnQuery();
922 // Update the sticky preferences, in case we received a value
924 this.updateStickyPreferences();
926 // Only update and fetch new results if it is requested
927 if ( fetchChangesList
) {
928 this.updateChangesList();
933 * Update the list of changes and notify the model
935 * @param {Object} [params] Extra parameters to add to the API call
936 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
937 * @return {jQuery.Promise} Promise that is resolved when the update is complete
939 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
940 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
942 if ( updateMode
=== this.FILTER_CHANGE
) {
943 this.uriProcessor
.updateURL( params
);
945 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
946 this.changesListModel
.invalidate();
948 this.changesListModel
.setNewChangesExist( false );
949 this.updatingChangesList
= true;
950 return this._fetchChangesList()
953 function ( pieces
) {
954 var $changesListContent
= pieces
.changes
,
955 $fieldset
= pieces
.fieldset
;
956 this.changesListModel
.update(
959 pieces
.noResultsDetails
,
961 // separator between old and new changes
962 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
965 // Do nothing for failure
967 .always( function () {
968 this.updatingChangesList
= false;
973 * Get an object representing the default parameter state, whether
974 * it is from the model defaults or from the saved queries.
976 * @return {Object} Default parameters
978 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
979 if ( this.savedQueriesModel
.getDefault() ) {
980 return this.savedQueriesModel
.getDefaultParams();
982 return this.filtersModel
.getDefaultParams();
987 * Query the list of changes from the server for the current filters
989 * @param {string} counterId Id for this request. To allow concurrent requests
990 * not to invalidate each other.
991 * @param {Object} [params={}] Parameters to add to the query
993 * @return {jQuery.Promise} Promise object resolved with { content, status }
995 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
996 var uri
= this.uriProcessor
.getUpdatedUri(),
997 stickyParams
= this.filtersModel
.getStickyParamsValues(),
1001 params
= params
|| {};
1002 params
.action
= 'render'; // bypasses MW chrome
1004 uri
.extend( params
);
1006 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1007 requestId
= ++this.requestCounter
[ counterId
];
1008 latestRequest = function () {
1009 return requestId
=== this.requestCounter
[ counterId
];
1012 // Sticky parameters override the URL params
1013 // this is to make sure that whether we represent
1014 // the sticky params in the URL or not (they may
1015 // be normalized out) the sticky parameters are
1016 // always being sent to the server with their
1017 // current/default values
1018 uri
.extend( stickyParams
);
1020 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1022 function ( content
, message
, jqXHR
) {
1023 if ( !latestRequest() ) {
1024 return $.Deferred().reject();
1028 status
: jqXHR
.status
1031 // RC returns 404 when there is no results
1032 function ( jqXHR
) {
1033 if ( latestRequest() ) {
1034 return $.Deferred().resolve(
1036 content
: jqXHR
.responseText
,
1037 status
: jqXHR
.status
1046 * Fetch the list of changes from the server for the current filters
1048 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1051 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1052 return this._queryChangesList( 'updateChangesList' )
1057 // Status code 0 is not HTTP status code,
1058 // but is valid value of XMLHttpRequest status.
1059 // It is used for variety of network errors, for example
1060 // when an AJAX call was cancelled before getting the response
1061 if ( data
&& data
.status
=== 0 ) {
1063 changes
: 'NO_RESULTS',
1064 // We need empty result set, to avoid exceptions because of undefined value
1066 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1070 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1071 data
? data
.content
: ''
1074 return this._extractChangesListInfo( $parsed
);
1080 * Track usage of highlight feature
1082 * @param {string} action
1083 * @param {Array|Object|string} filters
1085 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1086 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1087 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1089 'event.ChangesListHighlights',
1093 userId
: mw
.user
.getId()
1099 * Track filter grouping usage
1101 * @param {string} action Action taken
1103 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1104 var controller
= this,
1105 rightNow
= new Date().getTime(),
1106 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1107 // Get all current filters
1108 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1109 return item
.getName();
1112 action
= action
|| 'filtermenu';
1114 // Check if these filters were the ones we just logged previously
1115 // (Don't log the same grouping twice, in case the user opens/closes)
1116 // the menu without action, or with the same result
1118 // Only log if the two arrays are different in size
1119 filters
.length
!== this.prevLoggedItems
.length
||
1120 // Or if any filters are not the same as the cached filters
1121 filters
.some( function ( filterName
) {
1122 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1124 // Or if any cached filters are not the same as given filters
1125 this.prevLoggedItems
.some( function ( filterName
) {
1126 return filters
.indexOf( filterName
) === -1;
1129 filters
.forEach( function ( filterName
) {
1131 'event.ChangesListFilterGrouping',
1134 groupIdentifier
: randomIdentifier
,
1136 userId
: mw
.user
.getId()
1141 // Cache the filter names
1142 this.prevLoggedItems
= filters
;
1147 * Apply a change of parameters to the model state, and check whether
1148 * the new state is different than the old state.
1150 * @param {Object} newParamState New parameter state to apply
1151 * @return {boolean} New applied model state is different than the previous state
1153 mw
.rcfilters
.Controller
.prototype.applyParamChange = function ( newParamState
) {
1155 before
= this.filtersModel
.getSelectedState();
1157 this.filtersModel
.updateStateFromParams( newParamState
);
1159 after
= this.filtersModel
.getSelectedState();
1161 return !OO
.compare( before
, after
);
1165 * Mark all changes as seen on Watchlist
1167 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1168 var api
= new mw
.Api();
1169 api
.postWithToken( 'csrf', {
1171 action
: 'setnotificationtimestamp',
1172 entirewatchlist
: true
1173 } ).then( function () {
1174 this.updateChangesList( null, 'markSeen' );
1177 }( mediaWiki
, jQuery
) );