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(),
142 true // We're using existing DOM elements
146 this.initializing
= false;
147 this.switchView( 'default' );
151 * Switch the view of the filters model
153 * @param {string} view Requested view
155 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
156 this.filtersModel
.switchView( view
);
160 * Reset to default filters
162 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
163 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
164 this.updateChangesList();
168 * Empty all selected filters
170 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
171 var highlightedFilterNames
= this.filtersModel
172 .getHighlightedItems()
173 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
175 this.filtersModel
.emptyAllFilters();
176 this.filtersModel
.clearAllHighlightColors();
177 // Check all filter interactions
178 this.filtersModel
.reassessFilterInteractions();
180 this.updateChangesList();
182 if ( highlightedFilterNames
) {
183 this._trackHighlight( 'clearAll', highlightedFilterNames
);
188 * Update the selected state of a filter
190 * @param {string} filterName Filter name
191 * @param {boolean} [isSelected] Filter selected state
193 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
194 var filterItem
= this.filtersModel
.getItemByName( filterName
);
197 // If no filter was found, break
201 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
203 if ( filterItem
.isSelected() !== isSelected
) {
204 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
206 this.updateChangesList();
208 // Check filter interactions
209 this.filtersModel
.reassessFilterInteractions( filterItem
);
214 * Clear both highlight and selection of a filter
216 * @param {string} filterName Name of the filter item
218 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
219 var filterItem
= this.filtersModel
.getItemByName( filterName
),
220 isHighlighted
= filterItem
.isHighlighted();
222 if ( filterItem
.isSelected() || isHighlighted
) {
223 this.filtersModel
.clearHighlightColor( filterName
);
224 this.filtersModel
.toggleFilterSelected( filterName
, false );
225 this.updateChangesList();
226 this.filtersModel
.reassessFilterInteractions( filterItem
);
228 // Log filter grouping
229 this.trackFilterGroupings( 'removefilter' );
232 if ( isHighlighted
) {
233 this._trackHighlight( 'clear', filterName
);
238 * Toggle the highlight feature on and off
240 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
241 this.filtersModel
.toggleHighlight();
244 if ( this.filtersModel
.isHighlightEnabled() ) {
245 mw
.hook( 'RcFilters.highlight.enable' ).fire();
250 * Toggle the namespaces inverted feature on and off
252 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
253 this.filtersModel
.toggleInvertedNamespaces();
254 this.updateChangesList();
258 * Set the highlight color for a filter item
260 * @param {string} filterName Name of the filter item
261 * @param {string} color Selected color
263 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
264 this.filtersModel
.setHighlightColor( filterName
, color
);
266 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
270 * Clear highlight for a filter item
272 * @param {string} filterName Name of the filter item
274 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
275 this.filtersModel
.clearHighlightColor( filterName
);
277 this._trackHighlight( 'clear', filterName
);
281 * Enable or disable live updates.
282 * @param {boolean} enable True to enable, false to disable
284 mw
.rcfilters
.Controller
.prototype.toggleLiveUpdate = function ( enable
) {
285 if ( enable
&& !this.liveUpdateTimeout
) {
286 this._scheduleLiveUpdate();
287 } else if ( !enable
&& this.liveUpdateTimeout
) {
288 clearTimeout( this.liveUpdateTimeout
);
289 this.liveUpdateTimeout
= null;
294 * Set a timeout for the next live update.
297 mw
.rcfilters
.Controller
.prototype._scheduleLiveUpdate = function () {
298 this.liveUpdateTimeout
= setTimeout( this._doLiveUpdate
.bind( this ), 3000 );
302 * Perform a live update.
305 mw
.rcfilters
.Controller
.prototype._doLiveUpdate = function () {
306 var controller
= this;
307 this.updateChangesList( {}, true )
308 .always( function () {
309 if ( controller
.liveUpdateTimeout
) {
310 // Live update was not disabled in the meantime
311 controller
._scheduleLiveUpdate();
317 * Save the current model state as a saved query
319 * @param {string} [label] Label of the saved query
321 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
) {
322 var highlightedItems
= {},
323 highlightEnabled
= this.filtersModel
.isHighlightEnabled();
325 // Prepare highlights
326 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
327 highlightedItems
[ item
.getName() ] = highlightEnabled
?
328 item
.getHighlightColor() : null;
330 // These are filter states; highlight is stored as boolean
331 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
334 this.savedQueriesModel
.addNewQuery(
335 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
337 filters
: this.filtersModel
.getSelectedState(),
338 highlights
: highlightedItems
,
339 invert
: this.filtersModel
.areNamespacesInverted()
344 this._saveSavedQueries();
348 * Remove a saved query
350 * @param {string} queryID Query id
352 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
353 this.savedQueriesModel
.removeQuery( queryID
);
355 this._saveSavedQueries();
359 * Rename a saved query
361 * @param {string} queryID Query id
362 * @param {string} newLabel New label for the query
364 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
365 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
368 queryItem
.updateLabel( newLabel
);
370 this._saveSavedQueries();
374 * Set a saved query as default
376 * @param {string} queryID Query Id. If null is given, default
379 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
380 this.savedQueriesModel
.setDefault( queryID
);
381 this._saveSavedQueries();
387 * @param {string} queryID Query id
389 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
390 var data
, highlights
,
391 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
394 data
= queryItem
.getData();
395 highlights
= data
.highlights
;
397 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
398 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
400 // Update model state from filters
401 this.filtersModel
.toggleFiltersSelected( data
.filters
);
403 // Update namespace inverted property
404 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
406 // Update highlight state
407 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
408 this.filtersModel
.getItems().forEach( function ( filterItem
) {
409 var color
= highlights
[ filterItem
.getName() ];
411 filterItem
.setHighlightColor( color
);
413 filterItem
.clearHighlightColor();
417 // Check all filter interactions
418 this.filtersModel
.reassessFilterInteractions();
420 this.updateChangesList();
422 // Log filter grouping
423 this.trackFilterGroupings( 'savedfilters' );
428 * Check whether the current filter and highlight state exists
429 * in the saved queries model.
431 * @return {boolean} Query exists
433 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
434 var highlightedItems
= {};
436 // Prepare highlights of the current query
437 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
438 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
440 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
442 return this.savedQueriesModel
.findMatchingQuery(
444 filters
: this.filtersModel
.getSelectedState(),
445 highlights
: highlightedItems
,
446 invert
: this.filtersModel
.areNamespacesInverted()
452 * Get an object representing the base state of parameters
455 * This is meant to make sure that the saved queries that are
456 * in memory are always the same structure as what we would get
457 * by calling the current model's "getSelectedState" and by checking
460 * In cases where a user saved a query when the system had a certain
461 * set of filters, and then a filter was added to the system, we want
462 * to make sure that the stored queries can still be comparable to
463 * the current state, which means that we need the base state for
466 * - Saved queries are stored in "minimal" view (only changed filters
467 * are stored); When we initialize the system, we merge each minimal
468 * query with the base state (using 'getNormalizedFilters') so all
469 * saved queries have the exact same structure as what we would get
470 * by checking the getSelectedState of the filter.
471 * - When we save the queries, we minimize the object to only represent
472 * whatever has actually changed, rather than store the entire
473 * object. To check what actually is different so we can store it,
474 * we need to obtain a base state to compare against, this is
475 * what #_getMinimalFilterList does
477 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
478 var defaultParams
= this.filtersModel
.getDefaultParams(),
479 highlightedItems
= {};
481 // Prepare highlights
482 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
483 highlightedItems
[ item
.getName() ] = null;
485 highlightedItems
.highlight
= false;
487 this.baseFilterState
= {
488 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
489 highlights
: highlightedItems
,
495 * Get an object representing the base filter state of both
496 * filters and highlights. The structure is similar to what we use
497 * to store each query in the saved queries object:
503 * filterName: (string|null)
507 * @return {Object} Object representing the base state of
508 * parameters and highlights
510 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
511 return this.baseFilterState
;
515 * Get an object that holds only the parameters and highlights that have
516 * values different than the base default value.
518 * This is the reverse of the normalization we do initially on loading and
519 * initializing the saved queries model.
521 * @param {Object} valuesObject Object representing the state of both
522 * filters and highlights in its normalized version, to be minimized.
523 * @return {Object} Minimal filters and highlights list
525 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
526 var result
= { filters
: {}, highlights
: {} },
527 baseState
= this._getBaseFilterState();
530 $.each( valuesObject
.filters
, function ( name
, value
) {
531 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
532 result
.filters
[ name
] = value
;
536 $.each( valuesObject
.highlights
, function ( name
, value
) {
537 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
538 result
.highlights
[ name
] = value
;
546 * Save the current state of the saved queries model with all
547 * query item representation in the user settings.
549 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
551 state
= this.savedQueriesModel
.getState(),
554 // Minimize before save
555 $.each( state
.queries
, function ( queryID
, info
) {
556 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
560 stringified
= JSON
.stringify( state
);
562 if ( stringified
.length
> 65535 ) {
563 // Sanity check, since the preference can only hold that.
567 // Save the preference
568 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
569 // Update the preference for this session
570 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
574 * Synchronize the URL with the current state of the filters
575 * without adding an history entry.
577 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
578 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
582 * Update filter state (selection and highlighting) based
583 * on current URL values.
585 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
586 * list based on the updated model.
588 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
589 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
591 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
593 // Only update and fetch new results if it is requested
594 if ( fetchChangesList
) {
595 this.updateChangesList();
600 * Update the list of changes and notify the model
602 * @param {Object} [params] Extra parameters to add to the API call
603 * @param {boolean} [isLiveUpdate] Don't update the URL or invalidate the changes list
604 * @return {jQuery.Promise} Promise that is resolved when the update is complete
606 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
, isLiveUpdate
) {
607 if ( !isLiveUpdate
) {
608 this._updateURL( params
);
609 this.changesListModel
.invalidate();
611 return this._fetchChangesList()
614 function ( pieces
) {
615 var $changesListContent
= pieces
.changes
,
616 $fieldset
= pieces
.fieldset
;
617 this.changesListModel
.update( $changesListContent
, $fieldset
);
619 // Do nothing for failure
624 * Get an object representing the default parameter state, whether
625 * it is from the model defaults or from the saved queries.
627 * @return {Object} Default parameters
629 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
630 var data
, queryHighlights
,
632 savedHighlights
= {},
633 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
635 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
636 defaultSavedQueryItem
) {
638 data
= defaultSavedQueryItem
.getData();
640 queryHighlights
= data
.highlights
|| {};
641 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
643 // Translate highlights to parameters
644 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
645 $.each( queryHighlights
, function ( filterName
, color
) {
646 if ( filterName
!== 'highlights' ) {
647 savedHighlights
[ filterName
+ '_color' ] = color
;
651 return $.extend( true, {}, savedParams
, savedHighlights
, { invert
: data
.invert
} );
656 this.filtersModel
.getDefaultParams()
661 * Get an object representing the default parameter state, whether
662 * it is from the model defaults or from the saved queries.
664 * @return {Object} Default parameters
666 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
667 var data
, queryHighlights
,
669 savedHighlights
= {},
670 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
672 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
673 defaultSavedQueryItem
) {
675 data
= defaultSavedQueryItem
.getData();
677 queryHighlights
= data
.highlights
|| {};
678 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
680 // Translate highlights to parameters
681 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
682 $.each( queryHighlights
, function ( filterName
, color
) {
683 if ( filterName
!== 'highlights' ) {
684 savedHighlights
[ filterName
+ '_color' ] = color
;
688 return $.extend( true, {}, savedParams
, savedHighlights
);
691 return this.filtersModel
.getDefaultParams();
695 * Update the URL of the page to reflect current filters
697 * This should not be called directly from outside the controller.
698 * If an action requires changing the URL, it should either use the
699 * highlighting actions below, or call #updateChangesList which does
700 * the uri corrections already.
702 * @param {Object} [params] Extra parameters to add to the API call
704 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
705 var currentUri
= new mw
.Uri(),
706 updatedUri
= this._getUpdatedUri();
708 updatedUri
.extend( params
|| {} );
711 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
712 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
714 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
719 * Get an updated mw.Uri object based on the model state
721 * @return {mw.Uri} Updated Uri
723 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
724 var uri
= new mw
.Uri();
727 uri
.query
= this.uriProcessor
.minimizeQuery(
731 // We want to retain unrecognized params
732 // The uri params from model will override
733 // any recognized value in the current uri
734 // query, retain unrecognized params, and
735 // the result will then be minimized
737 this.uriProcessor
.getUriParametersFromModel(),
746 * Fetch the list of changes from the server for the current filters
748 * @return {jQuery.Promise} Promise object that will resolve with the changes list
749 * or with a string denoting no results.
751 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
752 var uri
= this._getUpdatedUri(),
753 requestId
= ++this.requestCounter
,
754 latestRequest = function () {
755 return requestId
=== this.requestCounter
;
758 return $.ajax( uri
.toString(), { contentType
: 'html' } )
763 if ( !latestRequest() ) {
764 return $.Deferred().reject();
767 $parsed
= $( $.parseHTML( html
) );
771 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
773 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
777 function ( responseObj
) {
780 if ( !latestRequest() ) {
781 return $.Deferred().reject();
784 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
786 // Force a resolve state to this promise
787 return $.Deferred().resolve( {
788 changes
: 'NO_RESULTS',
789 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
796 * Track usage of highlight feature
798 * @param {string} action
799 * @param {array|object|string} filters
801 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
802 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
803 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
805 'event.ChangesListHighlights',
809 userId
: mw
.user
.getId()
815 * Track filter grouping usage
817 * @param {string} action Action taken
819 mw
.rcfilters
.Controller
.prototype.trackFilterGroupings = function ( action
) {
820 var controller
= this,
821 rightNow
= new Date().getTime(),
822 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
823 // Get all current filters
824 filters
= this.filtersModel
.getSelectedItems().map( function ( item
) {
825 return item
.getName();
828 action
= action
|| 'filtermenu';
830 // Check if these filters were the ones we just logged previously
831 // (Don't log the same grouping twice, in case the user opens/closes)
832 // the menu without action, or with the same result
834 // Only log if the two arrays are different in size
835 filters
.length
!== this.prevLoggedItems
.length
||
836 // Or if any filters are not the same as the cached filters
837 filters
.some( function ( filterName
) {
838 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
840 // Or if any cached filters are not the same as given filters
841 this.prevLoggedItems
.some( function ( filterName
) {
842 return filters
.indexOf( filterName
) === -1;
845 filters
.forEach( function ( filterName
) {
847 'event.ChangesListFilterGrouping',
850 groupIdentifier
: randomIdentifier
,
852 userId
: mw
.user
.getId()
857 // Cache the filter names
858 this.prevLoggedItems
= filters
;
861 }( mediaWiki
, jQuery
) );