3 var byteLength
= require( 'mediawiki.String' ).byteLength
;
5 /* eslint no-underscore-dangle: "off" */
7 * Controller for the filters in Recent Changes
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 mw
.rcfilters
.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.requestCounter
= {};
35 this.baseFilterState
= {};
36 this.uriProcessor
= null;
37 this.initializing
= false;
38 this.wereSavedQueriesSaved
= false;
40 this.prevLoggedItems
= [];
42 this.FILTER_CHANGE
= 'filterChange';
43 this.SHOW_NEW_CHANGES
= 'showNewChanges';
44 this.LIVE_UPDATE
= 'liveUpdate';
48 OO
.initClass( mw
.rcfilters
.Controller
);
51 * Initialize the filter and parameter states
53 * @param {Array} filterStructure Filter definition and structure for the model
54 * @param {Object} [namespaceStructure] Namespace definition
55 * @param {Object} [tagList] Tag definition
56 * @param {Object} [conditionalViews] Conditional view definition
58 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
, conditionalViews
) {
59 var parsedSavedQueries
, pieces
,
60 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
61 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
63 views
= $.extend( true, {}, conditionalViews
),
68 if ( namespaceStructure
) {
70 $.each( namespaceStructure
, function ( namespaceID
, label
) {
71 // Build and clean up the individual namespace items definition
74 label
: label
|| mw
.msg( 'blanknamespace' ),
77 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
80 cssClass
: 'mw-changeslist-ns-' + namespaceID
85 title
: mw
.msg( 'namespaces' ),
88 // Group definition (single group)
89 name
: 'namespace', // parameter name is singular
90 type
: 'string_options',
91 title
: mw
.msg( 'namespaces' ),
92 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
113 title
: mw
.msg( 'rcfilters-view-tags' ),
116 // Group definition (single group)
117 name
: 'tagfilter', // Parameter name
118 type
: 'string_options',
119 title
: 'rcfilters-view-tags', // Message key
120 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
128 // Add parameter range operations
133 type
: 'single_option',
134 title
: '', // Because it's a hidden group, this title actually appears nowhere
136 allowArbitrary
: true,
137 validate
: $.isNumeric
,
139 min
: 0, // The server normalizes negative numbers to 0 results
142 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
143 'default': mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
145 filters
: displayConfig
.limitArray
.map( function ( num
) {
146 return controller
._createFilterDataFromNumber( num
, num
);
151 type
: 'single_option',
152 title
: '', // Because it's a hidden group, this title actually appears nowhere
154 allowArbitrary
: true,
155 validate
: $.isNumeric
,
158 max
: displayConfig
.maxDays
160 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
161 numToLabelFunc: function ( i
) {
162 return Number( i
) < 1 ?
163 ( Number( i
) * 24 ).toFixed( 2 ) :
166 'default': mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
169 // Hours (1, 2, 6, 12)
170 0.04166, 0.0833, 0.25, 0.5
172 ].concat( displayConfig
.daysArray
)
173 .map( function ( num
) {
174 return controller
._createFilterDataFromNumber(
176 // Convert fractions of days to number of hours for the labels
177 num
< 1 ? Math
.round( num
* 24 ) : num
189 title
: '', // Because it's a hidden group, this title actually appears nowhere
195 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
202 // Before we do anything, we need to see if we require additional items in the
203 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
204 // groups; if we ever expand it, this might need further generalization:
205 $.each( views
, function ( viewName
, viewData
) {
206 viewData
.groups
.forEach( function ( groupData
) {
207 var extraValues
= [];
208 if ( groupData
.allowArbitrary
) {
209 // If the value in the URI isn't in the group, add it
210 if ( uri
.query
[ groupData
.name
] !== undefined ) {
211 extraValues
.push( uri
.query
[ groupData
.name
] );
213 // If the default value isn't in the group, add it
214 if ( groupData
.default !== undefined ) {
215 extraValues
.push( String( groupData
.default ) );
217 controller
.addNumberValuesToGroup( groupData
, extraValues
);
222 // Initialize the model
223 this.filtersModel
.initializeFilters( filterStructure
, views
);
225 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
227 { normalizeTarget
: this.normalizeTarget
}
230 if ( !mw
.user
.isAnon() ) {
232 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
234 parsedSavedQueries
= {};
237 // Initialize saved queries
238 this.savedQueriesModel
.initialize( parsedSavedQueries
);
239 if ( this.savedQueriesModel
.isConverted() ) {
240 // Since we know we converted, we're going to re-save
241 // the queries so they are now migrated to the new format
242 this._saveSavedQueries();
246 // Check whether we need to load defaults.
247 // We do this by checking whether the current URI query
248 // contains any parameters recognized by the system.
249 // If it does, we load the given state.
250 // If it doesn't, we have no values at all, and we assume
251 // the user loads the base-page and we load defaults.
252 // Defaults should only be applied on load (if necessary)
254 this.initializing
= true;
256 if ( defaultSavedQueryExists
) {
257 // This came from the server, meaning that we have a default
258 // saved query, but the server could not load it, probably because
259 // it was pre-conversion to the new format.
260 // We need to load this query again
261 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
263 // There are either recognized parameters in the URL
264 // or there are none, but there is also no default
265 // saved query (so defaults are from the backend)
266 // We want to update the state but not fetch results
268 this.updateStateFromUrl( false );
270 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
272 // Update the changes list with the existing data
273 // so it gets processed
274 this.changesListModel
.update(
277 pieces
.noResultsDetails
,
278 true // We're using existing DOM elements
282 this.initializing
= false;
283 this.switchView( 'default' );
285 this.pollingRate
= mw
.config
.get( 'StructuredChangeFiltersLiveUpdatePollingRate' );
286 if ( this.pollingRate
) {
287 this._scheduleLiveUpdate();
292 * Extracts information from the changes list DOM
294 * @param {jQuery} $root Root DOM to find children from
295 * @param {boolean} [statusCode] Server response status code
296 * @return {Object} Information about changes list
297 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
298 * (either normally or as an error)
299 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
300 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
301 * @return {jQuery} return.fieldset Fieldset
303 mw
.rcfilters
.Controller
.prototype._extractChangesListInfo = function ( $root
, statusCode
) {
305 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
306 areResults
= !!$changesListContents
.length
,
307 checkForLogout
= !areResults
&& statusCode
=== 200;
309 // We check if user logged out on different tab/browser or the session has expired.
310 // 205 status code returned from the server, which indicates that we need to reload the page
311 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
312 // status code (if everything else goes well).
314 if ( checkForLogout
&& !!$root
.find( '#wpName1' ).length
) {
315 location
.reload( false );
320 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
321 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
325 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
326 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
327 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
328 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
329 } else if ( $root
.find( '.mw-changeslist-invalidtargetpage' ).length
) {
330 info
.noResultsDetails
= 'NO_RESULTS_INVALID_TARGET_PAGE';
332 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
340 * Create filter data from a number, for the filters that are numerical value
342 * @param {Number} num Number
343 * @param {Number} numForDisplay Number for the label
344 * @return {Object} Filter data
346 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
349 label
: mw
.language
.convertNumber( numForDisplay
)
354 * Add an arbitrary values to groups that allow arbitrary values
356 * @param {Object} groupData Group data
357 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
359 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
360 var controller
= this,
361 normalizeWithinRange = function ( range
, val
) {
362 if ( val
< range
.min
) {
363 return range
.min
; // Min
364 } else if ( val
>= range
.max
) {
365 return range
.max
; // Max
370 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
372 // Normalize the arbitrary values and the default value for a range
373 if ( groupData
.range
) {
374 arbitraryValues
= arbitraryValues
.map( function ( val
) {
375 return normalizeWithinRange( groupData
.range
, val
);
378 // Normalize the default, since that's user defined
379 if ( groupData
.default !== undefined ) {
380 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
384 // This is only true for single_option group
385 // We assume these are the only groups that will allow for
386 // arbitrary, since it doesn't make any sense for the other
388 arbitraryValues
.forEach( function ( val
) {
390 // If the group allows for arbitrary data
391 groupData
.allowArbitrary
&&
392 // and it is single_option (or string_options, but we
393 // don't have cases of those yet, nor do we plan to)
394 groupData
.type
=== 'single_option' &&
395 // and, if there is a validate method and it passes on
397 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
398 // but if that value isn't already in the definition
400 .map( function ( filterData
) {
401 return String( filterData
.name
);
403 .indexOf( String( val
) ) === -1
405 // Add the filter information
406 groupData
.filters
.push( controller
._createFilterDataFromNumber(
408 groupData
.numToLabelFunc
?
409 groupData
.numToLabelFunc( val
) :
413 // If there's a sort function set up, re-sort the values
414 if ( groupData
.sortFunc
) {
415 groupData
.filters
.sort( groupData
.sortFunc
);
422 * Reset to default filters
424 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
425 var params
= this._getDefaultParams();
426 if ( this.applyParamChange( params
) ) {
427 // Only update the changes list if there was a change to actual filters
428 this.updateChangesList();
430 this.uriProcessor
.updateURL( params
);
435 * Check whether the default values of the filters are all false.
437 * @return {boolean} Defaults are all false
439 mw
.rcfilters
.Controller
.prototype.areDefaultsEmpty = function () {
440 return $.isEmptyObject( this._getDefaultParams() );
444 * Empty all selected filters
446 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
447 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
448 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
450 if ( this.applyParamChange( {} ) ) {
451 // Only update the changes list if there was a change to actual filters
452 this.updateChangesList();
454 this.uriProcessor
.updateURL();
457 if ( highlightedFilterNames
) {
458 this._trackHighlight( 'clearAll', highlightedFilterNames
);
463 * Update the selected state of a filter
465 * @param {string} filterName Filter name
466 * @param {boolean} [isSelected] Filter selected state
468 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
469 var filterItem
= this.filtersModel
.getItemByName( filterName
);
472 // If no filter was found, break
476 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
478 if ( filterItem
.isSelected() !== isSelected
) {
479 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
481 this.updateChangesList();
483 // Check filter interactions
484 this.filtersModel
.reassessFilterInteractions( filterItem
);
489 * Clear both highlight and selection of a filter
491 * @param {string} filterName Name of the filter item
493 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
494 var filterItem
= this.filtersModel
.getItemByName( filterName
),
495 isHighlighted
= filterItem
.isHighlighted(),
496 isSelected
= filterItem
.isSelected();
498 if ( isSelected
|| isHighlighted
) {
499 this.filtersModel
.clearHighlightColor( filterName
);
500 this.filtersModel
.toggleFilterSelected( filterName
, false );
503 // Only update the changes list if the filter changed
504 // its selection state. If it only changed its highlight
506 this.updateChangesList();
509 this.filtersModel
.reassessFilterInteractions( filterItem
);
511 // Log filter grouping
512 this.trackFilterGroupings( 'removefilter' );
515 if ( isHighlighted
) {
516 this._trackHighlight( 'clear', filterName
);
521 * Toggle the highlight feature on and off
523 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
524 this.filtersModel
.toggleHighlight();
525 this.uriProcessor
.updateURL();
527 if ( this.filtersModel
.isHighlightEnabled() ) {
528 mw
.hook( 'RcFilters.highlight.enable' ).fire();
533 * Toggle the namespaces inverted feature on and off
535 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
536 this.filtersModel
.toggleInvertedNamespaces();
538 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
539 function ( filterItem
) { return filterItem
.isSelected(); }
542 // Only re-fetch results if there are namespace items that are actually selected
543 this.updateChangesList();
545 this.uriProcessor
.updateURL();
550 * Set the value of the 'showlinkedto' parameter
551 * @param {boolean} value
553 mw
.rcfilters
.Controller
.prototype.setShowLinkedTo = function ( value
) {
554 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
555 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
557 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
558 this.uriProcessor
.updateURL();
559 // reload the results only when target is set
560 if ( targetItem
.getValue() ) {
561 this.updateChangesList();
566 * Set the target page
567 * @param {string} page
569 mw
.rcfilters
.Controller
.prototype.setTargetPage = function ( page
) {
570 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
571 targetItem
.setValue( page
);
572 this.uriProcessor
.updateURL();
573 this.updateChangesList();
577 * Set the highlight color for a filter item
579 * @param {string} filterName Name of the filter item
580 * @param {string} color Selected color
582 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
583 this.filtersModel
.setHighlightColor( filterName
, color
);
584 this.uriProcessor
.updateURL();
585 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
589 * Clear highlight for a filter item
591 * @param {string} filterName Name of the filter item
593 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
594 this.filtersModel
.clearHighlightColor( filterName
);
595 this.uriProcessor
.updateURL();
596 this._trackHighlight( 'clear', filterName
);
600 * Enable or disable live updates.
601 * @param {boolean} enable True to enable, false to disable
603 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
604 this.changesListModel
.toggleLiveUpdate( enable
);
605 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
606 this.updateChangesList( null, this.LIVE_UPDATE
);
611 * Set a timeout for the next live update.
614 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
615 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
619 * Perform a live update.
622 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
623 if ( !this._shouldCheckForNewChanges() ) {
624 // skip this turn and check back later
625 this._scheduleLiveUpdate();
629 this._checkForNewChanges()
630 .then( function ( statusCode
) {
631 // no result is 204 with the 'peek' param
633 var newChanges
= statusCode
=== 200;
635 if ( !this._shouldCheckForNewChanges() ) {
636 // by the time the response is received,
637 // it may not be appropriate anymore
641 // 205 is the status code returned from server when user's logged in/out
642 // status is not matching while fetching live update changes.
643 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
645 if ( statusCode
=== 205 ) {
646 location
.reload( false );
651 if ( this.changesListModel
.getLiveUpdate() ) {
652 return this.updateChangesList( null, this.LIVE_UPDATE
);
654 this.changesListModel
.setNewChangesExist( true );
658 .always( this._scheduleLiveUpdate
.bind( this ) );
662 * @return {boolean} It's appropriate to check for new changes now
665 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
666 return !document
.hidden
&&
667 !this.filtersModel
.hasConflict() &&
668 !this.changesListModel
.getNewChangesExist() &&
669 !this.updatingChangesList
&&
670 this.changesListModel
.getNextFrom();
674 * Check if new changes, newer than those currently shown, are available
676 * @return {jQuery.Promise} Promise object that resolves with a bool
677 * specifying if there are new changes or not
681 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
684 peek
: 1, // bypasses ChangesList specific UI
685 from: this.changesListModel
.getNextFrom(),
686 isAnon
: mw
.user
.isAnon()
688 return this._queryChangesList( 'liveUpdate', params
).then(
696 * Show the new changes
698 * @return {jQuery.Promise} Promise object that resolves after
699 * fetching and showing the new changes
701 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
702 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
706 * Save the current model state as a saved query
708 * @param {string} [label] Label of the saved query
709 * @param {boolean} [setAsDefault=false] This query should be set as the default
711 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
713 this.savedQueriesModel
.addNewQuery(
714 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
715 this.filtersModel
.getCurrentParameterState( true ),
720 this._saveSavedQueries();
724 * Remove a saved query
726 * @param {string} queryID Query id
728 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
729 this.savedQueriesModel
.removeQuery( queryID
);
731 this._saveSavedQueries();
735 * Rename a saved query
737 * @param {string} queryID Query id
738 * @param {string} newLabel New label for the query
740 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
741 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
744 queryItem
.updateLabel( newLabel
);
746 this._saveSavedQueries();
750 * Set a saved query as default
752 * @param {string} queryID Query Id. If null is given, default
755 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
756 this.savedQueriesModel
.setDefault( queryID
);
757 this._saveSavedQueries();
763 * @param {string} queryID Query id
765 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
766 var currentMatchingQuery
,
767 params
= this.savedQueriesModel
.getItemParams( queryID
);
769 currentMatchingQuery
= this.findQueryMatchingCurrentState();
772 currentMatchingQuery
&&
773 currentMatchingQuery
.getID() === queryID
775 // If the query we want to load is the one that is already
776 // loaded, don't reload it
780 if ( this.applyParamChange( params
) ) {
781 // Update changes list only if there was a difference in filter selection
782 this.updateChangesList();
784 this.uriProcessor
.updateURL( params
);
787 // Log filter grouping
788 this.trackFilterGroupings( 'savedfilters' );
792 * Check whether the current filter and highlight state exists
793 * in the saved queries model.
795 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
797 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
798 return this.savedQueriesModel
.findMatchingQuery(
799 this.filtersModel
.getCurrentParameterState( true )
804 * Save the current state of the saved queries model with all
805 * query item representation in the user settings.
807 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
808 var stringified
, oldPrefValue
,
809 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
810 state
= this.savedQueriesModel
.getState();
813 stringified
= JSON
.stringify( state
);
815 if ( byteLength( stringified
) > 65535 ) {
816 // Sanity check, since the preference can only hold that.
820 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
821 // The queries were converted from the previous version
822 // Keep the old string in the [prefname]-versionbackup
823 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
825 // Save the old preference in the backup preference
826 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
827 // Update the preference for this session
828 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
831 // Save the preference
832 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
833 // Update the preference for this session
834 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
836 // Tag as already saved so we don't do this again
837 this.wereSavedQueriesSaved
= true;
841 * Update sticky preferences with current model state
843 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
844 // Update default sticky values with selected, whether they came from
845 // the initial defaults or from the URL value that is being normalized
846 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).findSelectedItems()[ 0 ].getParamName() );
847 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).findSelectedItems()[ 0 ].getParamName() );
849 // TODO: Make these automatic by having the model go over sticky
850 // items and update their default values automatically
854 * Update the limit default value
856 * @param {number} newValue New value
858 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( newValue
) {
859 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
863 * Update the days default value
865 * @param {number} newValue New value
867 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( newValue
) {
868 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
872 * Update the group by page default value
874 * @param {boolean} newValue New value
876 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
877 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
881 * Update the collapsed state value
883 * @param {boolean} isCollapsed Filter area is collapsed
885 mw
.rcfilters
.Controller
.prototype.updateCollapsedState = function ( isCollapsed
) {
886 this.updateNumericPreference( this.collapsedPreferenceName
, Number( isCollapsed
) );
890 * Update a numeric preference with a new value
892 * @param {string} prefName Preference name
893 * @param {number|string} newValue New value
895 mw
.rcfilters
.Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
896 if ( !$.isNumeric( newValue
) ) {
900 newValue
= Number( newValue
);
902 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
903 // Save the preference
904 new mw
.Api().saveOption( prefName
, newValue
);
905 // Update the preference for this session
906 mw
.user
.options
.set( prefName
, newValue
);
911 * Synchronize the URL with the current state of the filters
912 * without adding an history entry.
914 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
915 this.uriProcessor
.updateURL();
919 * Update filter state (selection and highlighting) based
920 * on current URL values.
922 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
923 * list based on the updated model.
925 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
926 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
928 this.uriProcessor
.updateModelBasedOnQuery();
930 // Update the sticky preferences, in case we received a value
932 this.updateStickyPreferences();
934 // Only update and fetch new results if it is requested
935 if ( fetchChangesList
) {
936 this.updateChangesList();
941 * Update the list of changes and notify the model
943 * @param {Object} [params] Extra parameters to add to the API call
944 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
945 * @return {jQuery.Promise} Promise that is resolved when the update is complete
947 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
948 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
950 if ( updateMode
=== this.FILTER_CHANGE
) {
951 this.uriProcessor
.updateURL( params
);
953 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
954 this.changesListModel
.invalidate();
956 this.changesListModel
.setNewChangesExist( false );
957 this.updatingChangesList
= true;
958 return this._fetchChangesList()
961 function ( pieces
) {
962 var $changesListContent
= pieces
.changes
,
963 $fieldset
= pieces
.fieldset
;
964 this.changesListModel
.update(
967 pieces
.noResultsDetails
,
969 // separator between old and new changes
970 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
973 // Do nothing for failure
975 .always( function () {
976 this.updatingChangesList
= false;
981 * Get an object representing the default parameter state, whether
982 * it is from the model defaults or from the saved queries.
984 * @return {Object} Default parameters
986 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
987 if ( this.savedQueriesModel
.getDefault() ) {
988 return this.savedQueriesModel
.getDefaultParams();
990 return this.filtersModel
.getDefaultParams();
995 * Query the list of changes from the server for the current filters
997 * @param {string} counterId Id for this request. To allow concurrent requests
998 * not to invalidate each other.
999 * @param {Object} [params={}] Parameters to add to the query
1001 * @return {jQuery.Promise} Promise object resolved with { content, status }
1003 mw
.rcfilters
.Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1004 var uri
= this.uriProcessor
.getUpdatedUri(),
1005 stickyParams
= this.filtersModel
.getStickyParamsValues(),
1009 params
= params
|| {};
1010 params
.action
= 'render'; // bypasses MW chrome
1012 uri
.extend( params
);
1014 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1015 requestId
= ++this.requestCounter
[ counterId
];
1016 latestRequest = function () {
1017 return requestId
=== this.requestCounter
[ counterId
];
1020 // Sticky parameters override the URL params
1021 // this is to make sure that whether we represent
1022 // the sticky params in the URL or not (they may
1023 // be normalized out) the sticky parameters are
1024 // always being sent to the server with their
1025 // current/default values
1026 uri
.extend( stickyParams
);
1028 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1030 function ( content
, message
, jqXHR
) {
1031 if ( !latestRequest() ) {
1032 return $.Deferred().reject();
1036 status
: jqXHR
.status
1039 // RC returns 404 when there is no results
1040 function ( jqXHR
) {
1041 if ( latestRequest() ) {
1042 return $.Deferred().resolve(
1044 content
: jqXHR
.responseText
,
1045 status
: jqXHR
.status
1054 * Fetch the list of changes from the server for the current filters
1056 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1059 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
1060 return this._queryChangesList( 'updateChangesList' )
1065 // Status code 0 is not HTTP status code,
1066 // but is valid value of XMLHttpRequest status.
1067 // It is used for variety of network errors, for example
1068 // when an AJAX call was cancelled before getting the response
1069 if ( data
&& data
.status
=== 0 ) {
1071 changes
: 'NO_RESULTS',
1072 // We need empty result set, to avoid exceptions because of undefined value
1074 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1078 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1079 data
? data
.content
: ''
1082 return this._extractChangesListInfo( $parsed
, data
.status
);
1088 * Track usage of highlight feature
1090 * @param {string} action
1091 * @param {Array|Object|string} filters
1093 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1094 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1095 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1097 'event.ChangesListHighlights',
1101 userId
: mw
.user
.getId()
1107 * Track filter grouping usage
1109 * @param {string} action Action taken
1111 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1112 var controller
= this,
1113 rightNow
= new Date().getTime(),
1114 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1115 // Get all current filters
1116 filters
= this.filtersModel
.findSelectedItems().map( function ( item
) {
1117 return item
.getName();
1120 action
= action
|| 'filtermenu';
1122 // Check if these filters were the ones we just logged previously
1123 // (Don't log the same grouping twice, in case the user opens/closes)
1124 // the menu without action, or with the same result
1126 // Only log if the two arrays are different in size
1127 filters
.length
!== this.prevLoggedItems
.length
||
1128 // Or if any filters are not the same as the cached filters
1129 filters
.some( function ( filterName
) {
1130 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1132 // Or if any cached filters are not the same as given filters
1133 this.prevLoggedItems
.some( function ( filterName
) {
1134 return filters
.indexOf( filterName
) === -1;
1137 filters
.forEach( function ( filterName
) {
1139 'event.ChangesListFilterGrouping',
1142 groupIdentifier
: randomIdentifier
,
1144 userId
: mw
.user
.getId()
1149 // Cache the filter names
1150 this.prevLoggedItems
= filters
;
1155 * Apply a change of parameters to the model state, and check whether
1156 * the new state is different than the old state.
1158 * @param {Object} newParamState New parameter state to apply
1159 * @return {boolean} New applied model state is different than the previous state
1161 mw
.rcfilters
.Controller
.prototype.applyParamChange = function ( newParamState
) {
1163 before
= this.filtersModel
.getSelectedState();
1165 this.filtersModel
.updateStateFromParams( newParamState
);
1167 after
= this.filtersModel
.getSelectedState();
1169 return !OO
.compare( before
, after
);
1173 * Mark all changes as seen on Watchlist
1175 mw
.rcfilters
.Controller
.prototype.markAllChangesAsSeen = function () {
1176 var api
= new mw
.Api();
1177 api
.postWithToken( 'csrf', {
1179 action
: 'setnotificationtimestamp',
1180 entirewatchlist
: true
1181 } ).then( function () {
1182 this.updateChangesList( null, 'markSeen' );
1187 * Set the current search for the system.
1189 * @param {string} searchQuery Search query, including triggers
1191 mw
.rcfilters
.Controller
.prototype.setSearch = function ( searchQuery
) {
1192 this.filtersModel
.setSearch( searchQuery
);
1196 * Switch the view by changing the search query trigger
1197 * without changing the search term
1199 * @param {string} view View to change to
1201 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
1203 this.filtersModel
.getViewTrigger( view
) +
1204 this.filtersModel
.removeViewTriggers( this.filtersModel
.getSearch() )
1209 * Reset the search for a specific view. This means we null the search query
1210 * and replace it with the relevant trigger for the requested view
1212 * @param {string} [view='default'] View to change to
1214 mw
.rcfilters
.Controller
.prototype.resetSearchForView = function ( view
) {
1215 view
= view
|| 'default';
1218 this.filtersModel
.getViewTrigger( view
)
1221 }( mediaWiki
, jQuery
) );