2 /* eslint no-underscore-dangle: "off" */
4 * Controller for the filters in Recent Changes
6 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
7 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
8 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
10 mw
.rcfilters
.Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
) {
11 this.filtersModel
= filtersModel
;
12 this.changesListModel
= changesListModel
;
13 this.savedQueriesModel
= savedQueriesModel
;
14 this.requestCounter
= 0;
15 this.baseFilterState
= {};
16 this.uriProcessor
= null;
17 this.initializing
= false;
19 this.prevLoggedItems
= [];
23 OO
.initClass( mw
.rcfilters
.Controller
);
26 * Initialize the filter and parameter states
28 * @param {Array} filterStructure Filter definition and structure for the model
29 * @param {Object} [namespaceStructure] Namespace definition
30 * @param {Object} [tagList] Tag definition
32 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
33 var parsedSavedQueries
,
37 $changesList
= $( '.mw-changeslist' ).first().contents();
40 if ( namespaceStructure
) {
42 $.each( namespaceStructure
, function ( namespaceID
, label
) {
43 // Build and clean up the individual namespace items definition
46 label
: label
|| mw
.msg( 'blanknamespace' ),
49 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
52 cssClass
: 'mw-changeslist-ns-' + namespaceID
57 title
: mw
.msg( 'namespaces' ),
60 // Group definition (single group)
61 name
: 'namespace', // parameter name is singular
62 type
: 'string_options',
63 title
: mw
.msg( 'namespaces' ),
64 labelPrefixKey
: { 'default': 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
73 title
: mw
.msg( 'rcfilters-view-tags' ),
76 // Group definition (single group)
77 name
: 'tagfilter', // Parameter name
78 type
: 'string_options',
79 title
: 'rcfilters-view-tags', // Message key
80 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
88 // Initialize the model
89 this.filtersModel
.initializeFilters( filterStructure
, views
);
91 this._buildBaseFilterState();
93 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
98 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
100 parsedSavedQueries
= {};
103 // The queries are saved in a minimized state, so we need
104 // to send over the base state so the saved queries model
105 // can normalize them per each query item
106 this.savedQueriesModel
.initialize(
108 this._getBaseFilterState()
111 // Check whether we need to load defaults.
112 // We do this by checking whether the current URI query
113 // contains any parameters recognized by the system.
114 // If it does, we load the given state.
115 // If it doesn't, we have no values at all, and we assume
116 // the user loads the base-page and we load defaults.
117 // Defaults should only be applied on load (if necessary)
119 this.initializing
= true;
121 this.savedQueriesModel
.getDefault() &&
122 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
124 // We have defaults from a saved query.
125 // We will load them straight-forward (as if
126 // they were clicked in the menu) so we trigger
127 // a full ajax request and change of URL
128 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
130 // There are either recognized parameters in the URL
131 // or there are none, but there is also no default
132 // saved query (so defaults are from the backend)
133 // We want to update the state but not fetch results
135 this.updateStateFromUrl( false );
137 // Update the changes list with the existing data
138 // so it gets processed
139 this.changesListModel
.update(
140 $changesList
.length
? $changesList
: 'NO_RESULTS',
141 $( 'fieldset.rcoptions' ).first()
145 this.initializing
= false;
146 this.switchView( 'default' );
150 * Switch the view of the filters model
152 * @param {string} view Requested view
154 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
155 this.filtersModel
.switchView( view
);
159 * Reset to default filters
161 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
162 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
163 this.updateChangesList();
167 * Empty all selected filters
169 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
170 var highlightedFilterNames
= this.filtersModel
171 .getHighlightedItems()
172 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
174 this.filtersModel
.emptyAllFilters();
175 this.filtersModel
.clearAllHighlightColors();
176 // Check all filter interactions
177 this.filtersModel
.reassessFilterInteractions();
179 this.updateChangesList();
181 if ( highlightedFilterNames
) {
182 this._trackHighlight( 'clearAll', highlightedFilterNames
);
187 * Update the selected state of a filter
189 * @param {string} filterName Filter name
190 * @param {boolean} [isSelected] Filter selected state
192 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
193 var filterItem
= this.filtersModel
.getItemByName( filterName
);
196 // If no filter was found, break
200 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
202 if ( filterItem
.isSelected() !== isSelected
) {
203 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
205 this.updateChangesList();
207 // Check filter interactions
208 this.filtersModel
.reassessFilterInteractions( filterItem
);
213 * Clear both highlight and selection of a filter
215 * @param {string} filterName Name of the filter item
217 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
218 var filterItem
= this.filtersModel
.getItemByName( filterName
),
219 isHighlighted
= filterItem
.isHighlighted();
221 if ( filterItem
.isSelected() || isHighlighted
) {
222 this.filtersModel
.clearHighlightColor( filterName
);
223 this.filtersModel
.toggleFilterSelected( filterName
, false );
224 this.updateChangesList();
225 this.filtersModel
.reassessFilterInteractions( filterItem
);
227 // Log filter grouping
228 this.trackFilterGroupings( 'removefilter' );
231 if ( isHighlighted
) {
232 this._trackHighlight( 'clear', filterName
);
237 * Toggle the highlight feature on and off
239 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
240 this.filtersModel
.toggleHighlight();
243 if ( this.filtersModel
.isHighlightEnabled() ) {
244 mw
.hook( 'RcFilters.highlight.enable' ).fire();
249 * Toggle the namespaces inverted feature on and off
251 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
252 this.filtersModel
.toggleInvertedNamespaces();
253 this.updateChangesList();
257 * Set the highlight color for a filter item
259 * @param {string} filterName Name of the filter item
260 * @param {string} color Selected color
262 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
263 this.filtersModel
.setHighlightColor( filterName
, color
);
265 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
269 * Clear highlight for a filter item
271 * @param {string} filterName Name of the filter item
273 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
274 this.filtersModel
.clearHighlightColor( filterName
);
276 this._trackHighlight( 'clear', filterName
);
280 * Enable or disable live updates.
281 * @param {boolean} enable True to enable, false to disable
283 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
284 if ( enable
&& !this.liveUpdateTimeout
) {
285 this._scheduleLiveUpdate();
286 } else if ( !enable
&& this.liveUpdateTimeout
) {
287 clearTimeout( this.liveUpdateTimeout
);
288 this.liveUpdateTimeout
= null;
293 * Set a timeout for the next live update.
296 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
297 this.liveUpdateTimeout
= setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
301 * Perform a live update.
304 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
305 var controller
= this;
306 this.updateChangesList( {}, true )
307 .always( function () {
308 if ( controller
.liveUpdateTimeout
) {
309 // Live update was not disabled in the meantime
310 controller
._scheduleLiveUpdate();
316 * Save the current model state as a saved query
318 * @param {string} [label] Label of the saved query
320 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
) {
321 var highlightedItems
= {},
322 highlightEnabled
= this.filtersModel
.isHighlightEnabled();
324 // Prepare highlights
325 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
326 highlightedItems
[ item
.getName() ] = highlightEnabled
?
327 item
.getHighlightColor() : null;
329 // These are filter states; highlight is stored as boolean
330 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
333 this.savedQueriesModel
.addNewQuery(
334 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
336 filters
: this.filtersModel
.getSelectedState(),
337 highlights
: highlightedItems
,
338 invert
: this.filtersModel
.areNamespacesInverted()
343 this._saveSavedQueries();
347 * Remove a saved query
349 * @param {string} queryID Query id
351 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
352 this.savedQueriesModel
.removeQuery( queryID
);
354 this._saveSavedQueries();
358 * Rename a saved query
360 * @param {string} queryID Query id
361 * @param {string} newLabel New label for the query
363 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
364 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
367 queryItem
.updateLabel( newLabel
);
369 this._saveSavedQueries();
373 * Set a saved query as default
375 * @param {string} queryID Query Id. If null is given, default
378 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
379 this.savedQueriesModel
.setDefault( queryID
);
380 this._saveSavedQueries();
386 * @param {string} queryID Query id
388 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
389 var data
, highlights
,
390 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
393 data
= queryItem
.getData();
394 highlights
= data
.highlights
;
396 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
397 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
399 // Update model state from filters
400 this.filtersModel
.toggleFiltersSelected( data
.filters
);
402 // Update namespace inverted property
403 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
405 // Update highlight state
406 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
407 this.filtersModel
.getItems().forEach( function ( filterItem
) {
408 var color
= highlights
[ filterItem
.getName() ];
410 filterItem
.setHighlightColor( color
);
412 filterItem
.clearHighlightColor();
416 // Check all filter interactions
417 this.filtersModel
.reassessFilterInteractions();
419 this.updateChangesList();
421 // Log filter grouping
422 this.trackFilterGroupings( 'savedfilters' );
427 * Check whether the current filter and highlight state exists
428 * in the saved queries model.
430 * @return {boolean} Query exists
432 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
433 var highlightedItems
= {};
435 // Prepare highlights of the current query
436 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
437 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
439 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
441 return this.savedQueriesModel
.findMatchingQuery(
443 filters
: this.filtersModel
.getSelectedState(),
444 highlights
: highlightedItems
,
445 invert
: this.filtersModel
.areNamespacesInverted()
451 * Get an object representing the base state of parameters
454 * This is meant to make sure that the saved queries that are
455 * in memory are always the same structure as what we would get
456 * by calling the current model's "getSelectedState" and by checking
459 * In cases where a user saved a query when the system had a certain
460 * set of filters, and then a filter was added to the system, we want
461 * to make sure that the stored queries can still be comparable to
462 * the current state, which means that we need the base state for
465 * - Saved queries are stored in "minimal" view (only changed filters
466 * are stored); When we initialize the system, we merge each minimal
467 * query with the base state (using 'getNormalizedFilters') so all
468 * saved queries have the exact same structure as what we would get
469 * by checking the getSelectedState of the filter.
470 * - When we save the queries, we minimize the object to only represent
471 * whatever has actually changed, rather than store the entire
472 * object. To check what actually is different so we can store it,
473 * we need to obtain a base state to compare against, this is
474 * what #_getMinimalFilterList does
476 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
477 var defaultParams
= this.filtersModel
.getDefaultParams(),
478 highlightedItems
= {};
480 // Prepare highlights
481 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
482 highlightedItems
[ item
.getName() ] = null;
484 highlightedItems
.highlight
= false;
486 this.baseFilterState
= {
487 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
488 highlights
: highlightedItems
,
494 * Get an object representing the base filter state of both
495 * filters and highlights. The structure is similar to what we use
496 * to store each query in the saved queries object:
502 * filterName: (string|null)
506 * @return {Object} Object representing the base state of
507 * parameters and highlights
509 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
510 return this.baseFilterState
;
514 * Get an object that holds only the parameters and highlights that have
515 * values different than the base default value.
517 * This is the reverse of the normalization we do initially on loading and
518 * initializing the saved queries model.
520 * @param {Object} valuesObject Object representing the state of both
521 * filters and highlights in its normalized version, to be minimized.
522 * @return {Object} Minimal filters and highlights list
524 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
525 var result
= { filters
: {}, highlights
: {} },
526 baseState
= this._getBaseFilterState();
529 $.each( valuesObject
.filters
, function ( name
, value
) {
530 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
531 result
.filters
[ name
] = value
;
535 $.each( valuesObject
.highlights
, function ( name
, value
) {
536 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
537 result
.highlights
[ name
] = value
;
545 * Save the current state of the saved queries model with all
546 * query item representation in the user settings.
548 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
550 state
= this.savedQueriesModel
.getState(),
553 // Minimize before save
554 $.each( state
.queries
, function ( queryID
, info
) {
555 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
559 stringified
= JSON
.stringify( state
);
561 if ( stringified
.length
> 65535 ) {
562 // Sanity check, since the preference can only hold that.
566 // Save the preference
567 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
568 // Update the preference for this session
569 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
573 * Synchronize the URL with the current state of the filters
574 * without adding an history entry.
576 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
577 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
581 * Update filter state (selection and highlighting) based
582 * on current URL values.
584 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
585 * list based on the updated model.
587 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
588 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
590 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
592 // Only update and fetch new results if it is requested
593 if ( fetchChangesList
) {
594 this.updateChangesList();
599 * Update the list of changes and notify the model
601 * @param {Object} [params] Extra parameters to add to the API call
602 * @param {boolean} [isLiveUpdate] Don't update the URL or invalidate the changes list
603 * @return {jQuery.Promise} Promise that is resolved when the update is complete
605 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, isLiveUpdate
) {
606 if ( !isLiveUpdate
) {
607 this._updateURL( params
);
608 this.changesListModel
.invalidate();
610 return this._fetchChangesList()
613 function ( pieces
) {
614 var $changesListContent
= pieces
.changes
,
615 $fieldset
= pieces
.fieldset
;
616 this.changesListModel
.update( $changesListContent
, $fieldset
);
618 // Do nothing for failure
623 * Get an object representing the default parameter state, whether
624 * it is from the model defaults or from the saved queries.
626 * @return {Object} Default parameters
628 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
629 var data
, queryHighlights
,
631 savedHighlights
= {},
632 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
634 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
635 defaultSavedQueryItem
) {
637 data
= defaultSavedQueryItem
.getData();
639 queryHighlights
= data
.highlights
|| {};
640 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
642 // Translate highlights to parameters
643 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
644 $.each( queryHighlights
, function ( filterName
, color
) {
645 if ( filterName
!== 'highlights' ) {
646 savedHighlights
[ filterName
+ '_color' ] = color
;
650 return $.extend( true, {}, savedParams
, savedHighlights
, { invert
: data
.invert
} );
655 this.filtersModel
.getDefaultParams()
660 * Get an object representing the default parameter state, whether
661 * it is from the model defaults or from the saved queries.
663 * @return {Object} Default parameters
665 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
666 var data
, queryHighlights
,
668 savedHighlights
= {},
669 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
671 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
672 defaultSavedQueryItem
) {
674 data
= defaultSavedQueryItem
.getData();
676 queryHighlights
= data
.highlights
|| {};
677 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
679 // Translate highlights to parameters
680 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
681 $.each( queryHighlights
, function ( filterName
, color
) {
682 if ( filterName
!== 'highlights' ) {
683 savedHighlights
[ filterName
+ '_color' ] = color
;
687 return $.extend( true, {}, savedParams
, savedHighlights
);
690 return this.filtersModel
.getDefaultParams();
694 * Update the URL of the page to reflect current filters
696 * This should not be called directly from outside the controller.
697 * If an action requires changing the URL, it should either use the
698 * highlighting actions below, or call #updateChangesList which does
699 * the uri corrections already.
701 * @param {Object} [params] Extra parameters to add to the API call
703 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
704 var currentUri
= new mw
.Uri(),
705 updatedUri
= this._getUpdatedUri();
707 updatedUri
.extend( params
|| {} );
710 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
711 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
713 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
718 * Get an updated mw.Uri object based on the model state
720 * @return {mw.Uri} Updated Uri
722 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
723 var uri
= new mw
.Uri();
726 uri
.query
= this.uriProcessor
.minimizeQuery(
730 // We want to retain unrecognized params
731 // The uri params from model will override
732 // any recognized value in the current uri
733 // query, retain unrecognized params, and
734 // the result will then be minimized
736 this.uriProcessor
.getUriParametersFromModel(),
745 * Fetch the list of changes from the server for the current filters
747 * @return {jQuery.Promise} Promise object that will resolve with the changes list
748 * or with a string denoting no results.
750 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
751 var uri
= this._getUpdatedUri(),
752 requestId
= ++this.requestCounter
,
753 latestRequest = function () {
754 return requestId
=== this.requestCounter
;
757 return $.ajax( uri
.toString(), { contentType
: 'html' } )
762 if ( !latestRequest() ) {
763 return $.Deferred().reject();
766 $parsed
= $( $.parseHTML( html
) );
770 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
772 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
776 function ( responseObj
) {
779 if ( !latestRequest() ) {
780 return $.Deferred().reject();
783 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
785 // Force a resolve state to this promise
786 return $.Deferred().resolve( {
787 changes
: 'NO_RESULTS',
788 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
795 * Track usage of highlight feature
797 * @param {string} action
798 * @param {array|object|string} filters
800 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
801 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
802 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
804 'event.ChangesListHighlights',
808 userId
: mw
.user
.getId()
814 * Track filter grouping usage
816 * @param {string} action Action taken
818 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
819 var controller
= this,
820 rightNow
= new Date().getTime(),
821 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
822 // Get all current filters
823 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
824 return item
.getName();
827 action
= action
|| 'filtermenu';
829 // Check if these filters were the ones we just logged previously
830 // (Don't log the same grouping twice, in case the user opens/closes)
831 // the menu without action, or with the same result
833 // Only log if the two arrays are different in size
834 filters
.length
!== this.prevLoggedItems
.length
||
835 // Or if any filters are not the same as the cached filters
836 filters
.some( function ( filterName
) {
837 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
839 // Or if any cached filters are not the same as given filters
840 this.prevLoggedItems
.some( function ( filterName
) {
841 return filters
.indexOf( filterName
) === -1;
844 filters
.forEach( function ( filterName
) {
846 'event.ChangesListFilterGrouping',
849 groupIdentifier
: randomIdentifier
,
851 userId
: mw
.user
.getId()
856 // Cache the filter names
857 this.prevLoggedItems
= filters
;
860 }( mediaWiki
, jQuery
) );