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
12 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
) {
13 this.filtersModel
= filtersModel
;
14 this.changesListModel
= changesListModel
;
15 this.savedQueriesModel
= savedQueriesModel
;
16 this.requestCounter
= {};
17 this.baseFilterState
= {};
18 this.uriProcessor
= null;
19 this.initializing
= false;
21 this.prevLoggedItems
= [];
25 OO
.initClass( mw
.rcfilters
.Controller
);
28 * Initialize the filter and parameter states
30 * @param {Array} filterStructure Filter definition and structure for the model
31 * @param {Object} [namespaceStructure] Namespace definition
32 * @param {Object} [tagList] Tag definition
34 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
35 var parsedSavedQueries
, limitDefault
,
36 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
41 $changesList
= $( '.mw-changeslist' ).first().contents();
44 if ( namespaceStructure
) {
46 $.each( namespaceStructure
, function ( namespaceID
, label
) {
47 // Build and clean up the individual namespace items definition
50 label
: label
|| mw
.msg( 'blanknamespace' ),
53 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
56 cssClass
: 'mw-changeslist-ns-' + namespaceID
61 title
: mw
.msg( 'namespaces' ),
64 // Group definition (single group)
65 name
: 'namespace', // parameter name is singular
66 type
: 'string_options',
67 title
: mw
.msg( 'namespaces' ),
68 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
77 title
: mw
.msg( 'rcfilters-view-tags' ),
80 // Group definition (single group)
81 name
: 'tagfilter', // Parameter name
82 type
: 'string_options',
83 title
: 'rcfilters-view-tags', // Message key
84 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
92 // Convert the default from the old preference
93 // since the limit preference actually affects more
94 // than just the RecentChanges page
95 limitDefault
= Number( mw
.user
.options
.get( 'rclimit', '50' ) );
97 // Add parameter range operations
102 type
: 'single_option',
103 title
: '', // Because it's a hidden group, this title actually appears nowhere
105 allowArbitrary
: true,
106 validate
: $.isNumeric
,
108 min
: 0, // The server normalizes negative numbers to 0 results
111 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
112 'default': String( limitDefault
),
113 // Temporarily making this not sticky until we resolve the problem
114 // with the misleading preference. Note that if this is to be permanent
115 // we should remove all sticky behavior methods completely
118 filters
: displayConfig
.limitArray
.map( function ( num
) {
119 return controller
._createFilterDataFromNumber( num
, num
);
124 type
: 'single_option',
125 title
: '', // Because it's a hidden group, this title actually appears nowhere
127 allowArbitrary
: true,
128 validate
: $.isNumeric
,
131 max
: displayConfig
.maxDays
133 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
134 numToLabelFunc: function ( i
) {
135 return Number( i
) < 1 ?
136 ( Number( i
) * 24 ).toFixed( 2 ) :
139 'default': mw
.user
.options
.get( 'rcdays', '30' ),
140 // Temporarily making this not sticky while limit is not sticky, see above
143 // Hours (1, 2, 6, 12)
144 0.04166, 0.0833, 0.25, 0.5
146 ].concat( displayConfig
.daysArray
)
147 .map( function ( num
) {
148 return controller
._createFilterDataFromNumber(
150 // Convert fractions of days to number of hours for the labels
151 num
< 1 ? Math
.round( num
* 24 ) : num
163 title
: '', // Because it's a hidden group, this title actually appears nowhere
169 'default': String( mw
.user
.options
.get( 'usenewrc', 0 ) )
176 // Before we do anything, we need to see if we require additional items in the
177 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
178 // groups; if we ever expand it, this might need further generalization:
179 $.each( views
, function ( viewName
, viewData
) {
180 viewData
.groups
.forEach( function ( groupData
) {
181 var extraValues
= [];
182 if ( groupData
.allowArbitrary
) {
183 // If the value in the URI isn't in the group, add it
184 if ( uri
.query
[ groupData
.name
] !== undefined ) {
185 extraValues
.push( uri
.query
[ groupData
.name
] );
187 // If the default value isn't in the group, add it
188 if ( groupData
.default !== undefined ) {
189 extraValues
.push( String( groupData
.default ) );
191 controller
.addNumberValuesToGroup( groupData
, extraValues
);
196 // Initialize the model
197 this.filtersModel
.initializeFilters( filterStructure
, views
);
199 this._buildBaseFilterState();
201 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
206 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
208 parsedSavedQueries
= {};
211 // The queries are saved in a minimized state, so we need
212 // to send over the base state so the saved queries model
213 // can normalize them per each query item
214 this.savedQueriesModel
.initialize(
216 this._getBaseFilterState(),
217 // This is for backwards compatibility - delete all sticky filter states
218 Object
.keys( this.filtersModel
.getStickyFiltersState() )
221 // Check whether we need to load defaults.
222 // We do this by checking whether the current URI query
223 // contains any parameters recognized by the system.
224 // If it does, we load the given state.
225 // If it doesn't, we have no values at all, and we assume
226 // the user loads the base-page and we load defaults.
227 // Defaults should only be applied on load (if necessary)
229 this.initializing
= true;
231 this.savedQueriesModel
.getDefault() &&
232 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
234 // We have defaults from a saved query.
235 // We will load them straight-forward (as if
236 // they were clicked in the menu) so we trigger
237 // a full ajax request and change of URL
238 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
240 // There are either recognized parameters in the URL
241 // or there are none, but there is also no default
242 // saved query (so defaults are from the backend)
243 // We want to update the state but not fetch results
245 this.updateStateFromUrl( false );
247 // Update the changes list with the existing data
248 // so it gets processed
249 this.changesListModel
.update(
250 $changesList
.length
? $changesList
: 'NO_RESULTS',
251 $( 'fieldset.rcoptions' ).first(),
252 true // We're using existing DOM elements
256 this.initializing
= false;
257 this.switchView( 'default' );
259 this._scheduleLiveUpdate();
263 * Create filter data from a number, for the filters that are numerical value
265 * @param {Number} num Number
266 * @param {Number} numForDisplay Number for the label
267 * @return {Object} Filter data
269 mw
.rcfilters
.Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
272 label
: mw
.language
.convertNumber( numForDisplay
)
277 * Add an arbitrary values to groups that allow arbitrary values
279 * @param {Object} groupData Group data
280 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
282 mw
.rcfilters
.Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
283 var controller
= this,
284 normalizeWithinRange = function ( range
, val
) {
285 if ( val
< range
.min
) {
286 return range
.min
; // Min
287 } else if ( val
>= range
.max
) {
288 return range
.max
; // Max
293 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
295 // Normalize the arbitrary values and the default value for a range
296 if ( groupData
.range
) {
297 arbitraryValues
= arbitraryValues
.map( function ( val
) {
298 return normalizeWithinRange( groupData
.range
, val
);
301 // Normalize the default, since that's user defined
302 if ( groupData
.default !== undefined ) {
303 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
307 // This is only true for single_option group
308 // We assume these are the only groups that will allow for
309 // arbitrary, since it doesn't make any sense for the other
311 arbitraryValues
.forEach( function ( val
) {
313 // If the group allows for arbitrary data
314 groupData
.allowArbitrary
&&
315 // and it is single_option (or string_options, but we
316 // don't have cases of those yet, nor do we plan to)
317 groupData
.type
=== 'single_option' &&
318 // and, if there is a validate method and it passes on
320 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
321 // but if that value isn't already in the definition
323 .map( function ( filterData
) {
324 return String( filterData
.name
);
326 .indexOf( String( val
) ) === -1
328 // Add the filter information
329 groupData
.filters
.push( controller
._createFilterDataFromNumber(
331 groupData
.numToLabelFunc
?
332 groupData
.numToLabelFunc( val
) :
336 // If there's a sort function set up, re-sort the values
337 if ( groupData
.sortFunc
) {
338 groupData
.filters
.sort( groupData
.sortFunc
);
345 * Switch the view of the filters model
347 * @param {string} view Requested view
349 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
350 this.filtersModel
.switchView( view
);
354 * Reset to default filters
356 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
357 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
359 this.updateChangesList();
363 * Empty all selected filters
365 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
366 var highlightedFilterNames
= this.filtersModel
367 .getHighlightedItems()
368 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
370 this.filtersModel
.emptyAllFilters();
371 this.filtersModel
.clearAllHighlightColors();
372 // Check all filter interactions
373 this.filtersModel
.reassessFilterInteractions();
375 this.updateChangesList();
377 if ( highlightedFilterNames
) {
378 this._trackHighlight( 'clearAll', highlightedFilterNames
);
383 * Update the selected state of a filter
385 * @param {string} filterName Filter name
386 * @param {boolean} [isSelected] Filter selected state
388 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
389 var filterItem
= this.filtersModel
.getItemByName( filterName
);
392 // If no filter was found, break
396 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
398 if ( filterItem
.isSelected() !== isSelected
) {
399 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
401 this.updateChangesList();
403 // Check filter interactions
404 this.filtersModel
.reassessFilterInteractions( filterItem
);
409 * Clear both highlight and selection of a filter
411 * @param {string} filterName Name of the filter item
413 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
414 var filterItem
= this.filtersModel
.getItemByName( filterName
),
415 isHighlighted
= filterItem
.isHighlighted();
417 if ( filterItem
.isSelected() || isHighlighted
) {
418 this.filtersModel
.clearHighlightColor( filterName
);
419 this.filtersModel
.toggleFilterSelected( filterName
, false );
420 this.updateChangesList();
421 this.filtersModel
.reassessFilterInteractions( filterItem
);
423 // Log filter grouping
424 this.trackFilterGroupings( 'removefilter' );
427 if ( isHighlighted
) {
428 this._trackHighlight( 'clear', filterName
);
433 * Toggle the highlight feature on and off
435 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
436 this.filtersModel
.toggleHighlight();
439 if ( this.filtersModel
.isHighlightEnabled() ) {
440 mw
.hook( 'RcFilters.highlight.enable' ).fire();
445 * Toggle the namespaces inverted feature on and off
447 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
448 this.filtersModel
.toggleInvertedNamespaces();
451 this.filtersModel
.getFiltersByView( 'namespaces' )
452 .filter( function ( filterItem
) {
453 return filterItem
.isSelected();
457 // Only re-fetch results if there are namespace items that are actually selected
458 this.updateChangesList();
463 * Set the highlight color for a filter item
465 * @param {string} filterName Name of the filter item
466 * @param {string} color Selected color
468 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
469 this.filtersModel
.setHighlightColor( filterName
, color
);
471 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
475 * Clear highlight for a filter item
477 * @param {string} filterName Name of the filter item
479 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
480 this.filtersModel
.clearHighlightColor( filterName
);
482 this._trackHighlight( 'clear', filterName
);
486 * Enable or disable live updates.
487 * @param {boolean} enable True to enable, false to disable
489 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
490 this.changesListModel
.toggleLiveUpdate( enable
);
491 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
492 this.showNewChanges();
497 * Set a timeout for the next live update.
500 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
501 setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
505 * Perform a live update.
508 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
509 if ( !this._shouldCheckForNewChanges() ) {
510 // skip this turn and check back later
511 this._scheduleLiveUpdate();
515 this._checkForNewChanges()
516 .then( function ( data
) {
517 if ( !this._shouldCheckForNewChanges() ) {
518 // by the time the response is received,
519 // it may not be appropriate anymore
523 if ( data
.changes
!== 'NO_RESULTS' ) {
524 if ( this.changesListModel
.getLiveUpdate() ) {
525 return this.updateChangesList( false, null, true, false );
527 this.changesListModel
.setNewChangesExist( true );
531 .always( this._scheduleLiveUpdate
.bind( this ) );
535 * @return {boolean} It's appropriate to check for new changes now
538 mw
.rcfilters
.Controller
.prototype._shouldCheckForNewChanges = function () {
539 var liveUpdateFeatureFlag
= mw
.config
.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
540 new mw
.Uri().query
.liveupdate
;
542 return !document
.hidden
&&
543 !this.changesListModel
.getNewChangesExist() &&
544 !this.updatingChangesList
&&
545 liveUpdateFeatureFlag
;
549 * Check if new changes, newer than those currently shown, are available
551 * @return {jQuery.Promise} Promise object that resolves after trying
552 * to fetch 1 change newer than the last known 'from' parameter value
556 mw
.rcfilters
.Controller
.prototype._checkForNewChanges = function () {
557 return this._fetchChangesList(
561 from: this.changesListModel
.getNextFrom()
567 * Show the new changes
569 * @return {jQuery.Promise} Promise object that resolves after
570 * fetching and showing the new changes
572 mw
.rcfilters
.Controller
.prototype.showNewChanges = function () {
573 return this.updateChangesList( false, null, true, true );
577 * Save the current model state as a saved query
579 * @param {string} [label] Label of the saved query
580 * @param {boolean} [setAsDefault=false] This query should be set as the default
582 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
584 highlightedItems
= {},
585 highlightEnabled
= this.filtersModel
.isHighlightEnabled(),
586 selectedState
= this.filtersModel
.getSelectedState();
588 // Prepare highlights
589 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
590 highlightedItems
[ item
.getName() ] = highlightEnabled
?
591 item
.getHighlightColor() : null;
593 // These are filter states; highlight is stored as boolean
594 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
596 // Delete all sticky filters
597 this._deleteStickyValuesFromFilterState( selectedState
);
600 queryID
= this.savedQueriesModel
.addNewQuery(
601 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
603 filters
: selectedState
,
604 highlights
: highlightedItems
,
605 invert
: this.filtersModel
.areNamespacesInverted()
609 if ( setAsDefault
) {
610 this.savedQueriesModel
.setDefault( queryID
);
614 this._saveSavedQueries();
618 * Remove a saved query
620 * @param {string} queryID Query id
622 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
623 this.savedQueriesModel
.removeQuery( queryID
);
625 this._saveSavedQueries();
629 * Rename a saved query
631 * @param {string} queryID Query id
632 * @param {string} newLabel New label for the query
634 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
635 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
638 queryItem
.updateLabel( newLabel
);
640 this._saveSavedQueries();
644 * Set a saved query as default
646 * @param {string} queryID Query Id. If null is given, default
649 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
650 this.savedQueriesModel
.setDefault( queryID
);
651 this._saveSavedQueries();
657 * @param {string} queryID Query id
659 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
660 var data
, highlights
,
661 queryItem
= this.savedQueriesModel
.getItemByID( queryID
),
662 currentMatchingQuery
= this.findQueryMatchingCurrentState();
667 // If there's already a query, don't reload it
668 // if it's the same as the one that already exists
669 !currentMatchingQuery
||
670 currentMatchingQuery
.getID() !== queryItem
.getID()
673 data
= queryItem
.getData();
674 highlights
= data
.highlights
;
676 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
677 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
679 // Update model state from filters
680 this.filtersModel
.toggleFiltersSelected(
681 // Merge filters with sticky values
682 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
685 // Update namespace inverted property
686 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
688 // Update highlight state
689 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
690 this.filtersModel
.getItems().forEach( function ( filterItem
) {
691 var color
= highlights
[ filterItem
.getName() ];
693 filterItem
.setHighlightColor( color
);
695 filterItem
.clearHighlightColor();
699 // Check all filter interactions
700 this.filtersModel
.reassessFilterInteractions();
702 this.updateChangesList();
704 // Log filter grouping
705 this.trackFilterGroupings( 'savedfilters' );
710 * Check whether the current filter and highlight state exists
711 * in the saved queries model.
713 * @return {boolean} Query exists
715 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
716 var highlightedItems
= {},
717 selectedState
= this.filtersModel
.getSelectedState();
719 // Prepare highlights of the current query
720 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
721 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
723 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
725 // Remove sticky filters
726 this._deleteStickyValuesFromFilterState( selectedState
);
728 return this.savedQueriesModel
.findMatchingQuery(
730 filters
: selectedState
,
731 highlights
: highlightedItems
,
732 invert
: this.filtersModel
.areNamespacesInverted()
738 * Delete sticky filters from given object
740 * @param {Object} filterState Filter state
742 mw
.rcfilters
.Controller
.prototype._deleteStickyValuesFromFilterState = function ( filterState
) {
743 // Remove sticky filters
744 $.each( this.filtersModel
.getStickyFiltersState(), function ( filterName
) {
745 delete filterState
[ filterName
];
750 * Get an object representing the base state of parameters
753 * This is meant to make sure that the saved queries that are
754 * in memory are always the same structure as what we would get
755 * by calling the current model's "getSelectedState" and by checking
758 * In cases where a user saved a query when the system had a certain
759 * set of filters, and then a filter was added to the system, we want
760 * to make sure that the stored queries can still be comparable to
761 * the current state, which means that we need the base state for
764 * - Saved queries are stored in "minimal" view (only changed filters
765 * are stored); When we initialize the system, we merge each minimal
766 * query with the base state (using 'getNormalizedFilters') so all
767 * saved queries have the exact same structure as what we would get
768 * by checking the getSelectedState of the filter.
769 * - When we save the queries, we minimize the object to only represent
770 * whatever has actually changed, rather than store the entire
771 * object. To check what actually is different so we can store it,
772 * we need to obtain a base state to compare against, this is
773 * what #_getMinimalFilterList does
775 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
776 var defaultParams
= this.filtersModel
.getDefaultParams(),
777 highlightedItems
= {};
779 // Prepare highlights
780 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
781 highlightedItems
[ item
.getName() ] = null;
783 highlightedItems
.highlight
= false;
785 this.baseFilterState
= {
786 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
787 highlights
: highlightedItems
,
793 * Get an object representing the base filter state of both
794 * filters and highlights. The structure is similar to what we use
795 * to store each query in the saved queries object:
801 * filterName: (string|null)
805 * @return {Object} Object representing the base state of
806 * parameters and highlights
808 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
809 return this.baseFilterState
;
813 * Get an object that holds only the parameters and highlights that have
814 * values different than the base default value.
816 * This is the reverse of the normalization we do initially on loading and
817 * initializing the saved queries model.
819 * @param {Object} valuesObject Object representing the state of both
820 * filters and highlights in its normalized version, to be minimized.
821 * @return {Object} Minimal filters and highlights list
823 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
824 var result
= { filters
: {}, highlights
: {} },
825 baseState
= this._getBaseFilterState();
828 $.each( valuesObject
.filters
, function ( name
, value
) {
829 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
830 result
.filters
[ name
] = value
;
834 $.each( valuesObject
.highlights
, function ( name
, value
) {
835 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
836 result
.highlights
[ name
] = value
;
844 * Save the current state of the saved queries model with all
845 * query item representation in the user settings.
847 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
849 state
= this.savedQueriesModel
.getState(),
852 // Minimize before save
853 $.each( state
.queries
, function ( queryID
, info
) {
854 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
858 stringified
= JSON
.stringify( state
);
860 if ( stringified
.length
> 65535 ) {
861 // Sanity check, since the preference can only hold that.
865 // Save the preference
866 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
867 // Update the preference for this session
868 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
872 * Update sticky preferences with current model state
874 mw
.rcfilters
.Controller
.prototype.updateStickyPreferences = function () {
875 // Update default sticky values with selected, whether they came from
876 // the initial defaults or from the URL value that is being normalized
877 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
878 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
880 // TODO: Make these automatic by having the model go over sticky
881 // items and update their default values automatically
885 * Update the limit default value
887 * param {number} newValue New value
889 mw
.rcfilters
.Controller
.prototype.updateLimitDefault = function ( /* newValue */ ) {
890 // HACK: Temporarily remove this from being sticky
894 if ( !$.isNumeric( newValue ) ) {
898 newValue = Number( newValue );
900 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
901 // Save the preference
902 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
903 // Update the preference for this session
904 mw.user.options.set( 'rcfilters-rclimit', newValue );
911 * Update the days default value
913 * param {number} newValue New value
915 mw
.rcfilters
.Controller
.prototype.updateDaysDefault = function ( /* newValue */ ) {
916 // HACK: Temporarily remove this from being sticky
920 if ( !$.isNumeric( newValue ) ) {
924 newValue = Number( newValue );
926 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
927 // Save the preference
928 new mw.Api().saveOption( 'rcdays', newValue );
929 // Update the preference for this session
930 mw.user.options.set( 'rcdays', newValue );
937 * Update the group by page default value
939 * @param {number} newValue New value
941 mw
.rcfilters
.Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
942 if ( !$.isNumeric( newValue
) ) {
946 newValue
= Number( newValue
);
948 if ( mw
.user
.options
.get( 'usenewrc' ) !== newValue
) {
949 // Save the preference
950 new mw
.Api().saveOption( 'usenewrc', newValue
);
951 // Update the preference for this session
952 mw
.user
.options
.set( 'usenewrc', newValue
);
957 * Synchronize the URL with the current state of the filters
958 * without adding an history entry.
960 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
961 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
965 * Update filter state (selection and highlighting) based
966 * on current URL values.
968 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
969 * list based on the updated model.
971 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
972 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
974 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
976 // Update the sticky preferences, in case we received a value
978 this.updateStickyPreferences();
980 // Only update and fetch new results if it is requested
981 if ( fetchChangesList
) {
982 this.updateChangesList();
987 * Update the list of changes and notify the model
989 * @param {boolean} [updateUrl=true] Whether the URL should be updated with the current state of the filters
990 * @param {Object} [params] Extra parameters to add to the API call
991 * @param {boolean} [isLiveUpdate=false] The purpose of this update is to show new results for the same filters
992 * @param {boolean} [invalidateCurrentChanges=true] Invalidate current changes by default (show spinner)
993 * @return {jQuery.Promise} Promise that is resolved when the update is complete
995 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( updateUrl
, params
, isLiveUpdate
, invalidateCurrentChanges
) {
996 updateUrl
= updateUrl
=== undefined ? true : updateUrl
;
997 invalidateCurrentChanges
= invalidateCurrentChanges
=== undefined ? true : invalidateCurrentChanges
;
999 this._updateURL( params
);
1001 if ( invalidateCurrentChanges
) {
1002 this.changesListModel
.invalidate();
1004 this.changesListModel
.setNewChangesExist( false );
1005 this.updatingChangesList
= true;
1006 return this._fetchChangesList()
1009 function ( pieces
) {
1010 var $changesListContent
= pieces
.changes
,
1011 $fieldset
= pieces
.fieldset
;
1012 this.changesListModel
.update( $changesListContent
, $fieldset
, false, isLiveUpdate
);
1014 // Do nothing for failure
1016 .always( function () {
1017 this.updatingChangesList
= false;
1022 * Get an object representing the default parameter state, whether
1023 * it is from the model defaults or from the saved queries.
1025 * @return {Object} Default parameters
1027 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
1028 var data
, queryHighlights
,
1030 savedHighlights
= {},
1031 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
1033 if ( defaultSavedQueryItem
) {
1034 data
= defaultSavedQueryItem
.getData();
1036 queryHighlights
= data
.highlights
|| {};
1037 savedParams
= this.filtersModel
.getParametersFromFilters(
1038 // Merge filters with sticky values
1039 $.extend( true, {}, data
.filters
, this.filtersModel
.getStickyFiltersState() )
1042 // Translate highlights to parameters
1043 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
1044 $.each( queryHighlights
, function ( filterName
, color
) {
1045 if ( filterName
!== 'highlights' ) {
1046 savedHighlights
[ filterName
+ '_color' ] = color
;
1050 return $.extend( true, {}, savedParams
, savedHighlights
);
1053 return this.filtersModel
.getDefaultParams();
1057 * Update the URL of the page to reflect current filters
1059 * This should not be called directly from outside the controller.
1060 * If an action requires changing the URL, it should either use the
1061 * highlighting actions below, or call #updateChangesList which does
1062 * the uri corrections already.
1064 * @param {Object} [params] Extra parameters to add to the API call
1066 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
1067 var currentUri
= new mw
.Uri(),
1068 updatedUri
= this._getUpdatedUri();
1070 updatedUri
.extend( params
|| {} );
1073 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
1074 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
1076 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
1081 * Get an updated mw.Uri object based on the model state
1083 * @return {mw.Uri} Updated Uri
1085 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
1086 var uri
= new mw
.Uri();
1089 uri
.query
= this.uriProcessor
.minimizeQuery(
1093 // We want to retain unrecognized params
1094 // The uri params from model will override
1095 // any recognized value in the current uri
1096 // query, retain unrecognized params, and
1097 // the result will then be minimized
1099 this.uriProcessor
.getUriParametersFromModel(),
1108 * Fetch the list of changes from the server for the current filters
1110 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1111 * not to invalidate each other.
1112 * @param {Object} [params={}] Parameters to add to the query
1114 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1115 * or with a string denoting no results.
1117 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function ( counterId
, params
) {
1118 var uri
= this._getUpdatedUri(),
1119 stickyParams
= this.filtersModel
.getStickyParams(),
1123 counterId
= counterId
|| 'updateChangesList';
1124 params
= params
|| {};
1126 uri
.extend( params
);
1128 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1129 requestId
= ++this.requestCounter
[ counterId
];
1130 latestRequest = function () {
1131 return requestId
=== this.requestCounter
[ counterId
];
1134 // Sticky parameters override the URL params
1135 // this is to make sure that whether we represent
1136 // the sticky params in the URL or not (they may
1137 // be normalized out) the sticky parameters are
1138 // always being sent to the server with their
1139 // current/default values
1140 uri
.extend( stickyParams
);
1142 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1147 if ( !latestRequest() ) {
1148 return $.Deferred().reject();
1151 $parsed
= $( $.parseHTML( html
) );
1155 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
1157 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1161 function ( responseObj
) {
1164 if ( !latestRequest() ) {
1165 return $.Deferred().reject();
1168 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
1170 // Force a resolve state to this promise
1171 return $.Deferred().resolve( {
1172 changes
: 'NO_RESULTS',
1173 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
1180 * Track usage of highlight feature
1182 * @param {string} action
1183 * @param {Array|Object|string} filters
1185 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
1186 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1187 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1189 'event.ChangesListHighlights',
1193 userId
: mw
.user
.getId()
1199 * Track filter grouping usage
1201 * @param {string} action Action taken
1203 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
1204 var controller
= this,
1205 rightNow
= new Date().getTime(),
1206 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1207 // Get all current filters
1208 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
1209 return item
.getName();
1212 action
= action
|| 'filtermenu';
1214 // Check if these filters were the ones we just logged previously
1215 // (Don't log the same grouping twice, in case the user opens/closes)
1216 // the menu without action, or with the same result
1218 // Only log if the two arrays are different in size
1219 filters
.length
!== this.prevLoggedItems
.length
||
1220 // Or if any filters are not the same as the cached filters
1221 filters
.some( function ( filterName
) {
1222 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1224 // Or if any cached filters are not the same as given filters
1225 this.prevLoggedItems
.some( function ( filterName
) {
1226 return filters
.indexOf( filterName
) === -1;
1229 filters
.forEach( function ( filterName
) {
1231 'event.ChangesListFilterGrouping',
1234 groupIdentifier
: randomIdentifier
,
1236 userId
: mw
.user
.getId()
1241 // Cache the filter names
1242 this.prevLoggedItems
= filters
;
1245 }( mediaWiki
, jQuery
) );