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;
19 OO
.initClass( mw
.rcfilters
.Controller
);
22 * Initialize the filter and parameter states
24 * @param {Array} filterStructure Filter definition and structure for the model
26 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
) {
27 var parsedSavedQueries
,
28 $changesList
= $( '.mw-changeslist' ).first().contents();
29 // Initialize the model
30 this.filtersModel
.initializeFilters( filterStructure
);
32 this._buildBaseFilterState();
35 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
37 parsedSavedQueries
= {};
40 // The queries are saved in a minimized state, so we need
41 // to send over the base state so the saved queries model
42 // can normalize them per each query item
43 this.savedQueriesModel
.initialize(
47 this.updateStateBasedOnUrl();
49 // Update the changes list with the existing data
50 // so it gets processed
51 this.changesListModel
.update(
52 $changesList
.length
? $changesList
: 'NO_RESULTS',
53 $( 'fieldset.rcoptions' ).first()
58 * Reset to default filters
60 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
61 this._updateModelState( this._getDefaultParams() );
62 this.updateChangesList();
66 * Empty all selected filters
68 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
69 var highlightedFilterNames
= this.filtersModel
70 .getHighlightedItems()
71 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
73 this.filtersModel
.emptyAllFilters();
74 this.filtersModel
.clearAllHighlightColors();
75 // Check all filter interactions
76 this.filtersModel
.reassessFilterInteractions();
78 this.updateChangesList();
80 if ( highlightedFilterNames
) {
81 this._trackHighlight( 'clearAll', highlightedFilterNames
);
86 * Update the selected state of a filter
88 * @param {string} filterName Filter name
89 * @param {boolean} [isSelected] Filter selected state
91 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
92 var filterItem
= this.filtersModel
.getItemByName( filterName
);
95 // If no filter was found, break
99 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
101 if ( filterItem
.isSelected() !== isSelected
) {
102 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
104 this.updateChangesList();
106 // Check filter interactions
107 this.filtersModel
.reassessFilterInteractions( filterItem
);
112 * Clear both highlight and selection of a filter
114 * @param {string} filterName Name of the filter item
116 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
117 var filterItem
= this.filtersModel
.getItemByName( filterName
),
118 isHighlighted
= filterItem
.isHighlighted();
120 if ( filterItem
.isSelected() || isHighlighted
) {
121 this.filtersModel
.clearHighlightColor( filterName
);
122 this.filtersModel
.toggleFilterSelected( filterName
, false );
123 this.updateChangesList();
124 this.filtersModel
.reassessFilterInteractions( filterItem
);
127 if ( isHighlighted
) {
128 this._trackHighlight( 'clear', filterName
);
133 * Toggle the highlight feature on and off
135 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
136 this.filtersModel
.toggleHighlight();
139 if ( this.filtersModel
.isHighlightEnabled() ) {
140 mw
.hook( 'RcFilters.highlight.enable' ).fire();
145 * Set the highlight color for a filter item
147 * @param {string} filterName Name of the filter item
148 * @param {string} color Selected color
150 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
151 this.filtersModel
.setHighlightColor( filterName
, color
);
153 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
157 * Clear highlight for a filter item
159 * @param {string} filterName Name of the filter item
161 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
162 this.filtersModel
.clearHighlightColor( filterName
);
164 this._trackHighlight( 'clear', filterName
);
168 * Save the current model state as a saved query
170 * @param {string} [label] Label of the saved query
172 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
) {
173 var highlightedItems
= {},
174 highlightEnabled
= this.filtersModel
.isHighlightEnabled();
176 // Prepare highlights
177 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
178 highlightedItems
[ item
.getName() ] = highlightEnabled
?
179 item
.getHighlightColor() : null;
181 highlightedItems
.highlights
= this.filtersModel
.isHighlightEnabled();
184 this.savedQueriesModel
.addNewQuery(
185 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
187 filters
: this.filtersModel
.getSelectedState(),
188 highlights
: highlightedItems
193 this._saveSavedQueries();
197 * Remove a saved query
199 * @param {string} queryID Query id
201 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
202 var query
= this.savedQueriesModel
.getItemByID( queryID
);
204 this.savedQueriesModel
.removeItems( [ query
] );
206 // Check if this item was the default
207 if ( this.savedQueriesModel
.getDefault() === queryID
) {
208 // Nulify the default
209 this.savedQueriesModel
.setDefault( null );
211 this._saveSavedQueries();
215 * Rename a saved query
217 * @param {string} queryID Query id
218 * @param {string} newLabel New label for the query
220 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
221 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
224 queryItem
.updateLabel( newLabel
);
226 this._saveSavedQueries();
230 * Set a saved query as default
232 * @param {string} queryID Query Id. If null is given, default
235 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
236 this.savedQueriesModel
.setDefault( queryID
);
237 this._saveSavedQueries();
243 * @param {string} queryID Query id
245 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
246 var data
, highlights
,
247 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
250 data
= queryItem
.getData();
251 highlights
= data
.highlights
;
253 // Update model state from filters
254 this.filtersModel
.toggleFiltersSelected( data
.filters
);
256 // Update highlight state
257 this.filtersModel
.toggleHighlight( !!highlights
.highlights
);
258 this.filtersModel
.getItems().forEach( function ( filterItem
) {
259 var color
= highlights
[ filterItem
.getName() ];
261 filterItem
.setHighlightColor( color
);
263 filterItem
.clearHighlightColor();
267 // Check all filter interactions
268 this.filtersModel
.reassessFilterInteractions();
270 this.updateChangesList();
275 * Check whether the current filter and highlight state exists
276 * in the saved queries model.
278 * @return {boolean} Query exists
280 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
281 var highlightedItems
= {};
283 // Prepare highlights of the current query
284 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
285 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
287 highlightedItems
.highlights
= this.filtersModel
.isHighlightEnabled();
289 return this.savedQueriesModel
.findMatchingQuery(
291 filters
: this.filtersModel
.getSelectedState(),
292 highlights
: highlightedItems
298 * Get an object representing the base state of parameters
301 * This is meant to make sure that the saved queries that are
302 * in memory are always the same structure as what we would get
303 * by calling the current model's "getSelectedState" and by checking
306 * In cases where a user saved a query when the system had a certain
307 * set of filters, and then a filter was added to the system, we want
308 * to make sure that the stored queries can still be comparable to
309 * the current state, which means that we need the base state for
312 * - Saved queries are stored in "minimal" view (only changed filters
313 * are stored); When we initialize the system, we merge each minimal
314 * query with the base state (using 'getNormalizedFilters') so all
315 * saved queries have the exact same structure as what we would get
316 * by checking the getSelectedState of the filter.
317 * - When we save the queries, we minimize the object to only represent
318 * whatever has actually changed, rather than store the entire
319 * object. To check what actually is different so we can store it,
320 * we need to obtain a base state to compare against, this is
321 * what #_getMinimalFilterList does
323 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
324 var defaultParams
= this.filtersModel
.getDefaultParams(),
325 highlightedItems
= {};
327 // Prepare highlights
328 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
329 highlightedItems
[ item
.getName() ] = null;
331 highlightedItems
.highlights
= false;
334 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
335 highlights
: highlightedItems
340 * Get an object representing the base state of parameters
341 * and highlights. The structure is similar to what we use
342 * to store each query in the saved queries object:
348 * filterName: (string|null)
352 * @return {Object} Object representing the base state of
353 * parameters and highlights
355 mw
.rcfilters
.Controller
.prototype._getBaseState = function () {
356 return this.baseState
;
360 * Get an object that holds only the parameters and highlights that have
361 * values different than the base default value.
363 * This is the reverse of the normalization we do initially on loading and
364 * initializing the saved queries model.
366 * @param {Object} valuesObject Object representing the state of both
367 * filters and highlights in its normalized version, to be minimized.
368 * @return {Object} Minimal filters and highlights list
370 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
371 var result
= { filters
: {}, highlights
: {} },
372 baseState
= this._getBaseState();
375 $.each( valuesObject
.filters
, function ( name
, value
) {
376 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
377 result
.filters
[ name
] = value
;
381 $.each( valuesObject
.highlights
, function ( name
, value
) {
382 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
383 result
.highlights
[ name
] = value
;
391 * Save the current state of the saved queries model with all
392 * query item representation in the user settings.
394 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
396 state
= this.savedQueriesModel
.getState(),
399 // Minimize before save
400 $.each( state
.queries
, function ( queryID
, info
) {
401 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
405 stringified
= JSON
.stringify( state
);
407 if ( stringified
.length
> 65535 ) {
408 // Sanity check, since the preference can only hold that.
412 // Save the preference
413 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
414 // Update the preference for this session
415 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
419 * Synchronize the URL with the current state of the filters
420 * without adding an history entry.
422 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
423 window
.history
.replaceState(
424 { tag
: 'rcfilters' },
426 this._getUpdatedUri().toString()
431 * Update filter state (selection and highlighting) based
432 * on current URL and default values.
434 mw
.rcfilters
.Controller
.prototype.updateStateBasedOnUrl = function () {
435 var uri
= new mw
.Uri(),
436 defaultParams
= this._getDefaultParams();
438 this._updateModelState( $.extend( {}, defaultParams
, uri
.query
) );
439 this.updateChangesList();
443 * Update the list of changes and notify the model
445 * @param {Object} [params] Extra parameters to add to the API call
447 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
) {
448 this._updateURL( params
);
449 this.changesListModel
.invalidate();
450 this._fetchChangesList()
453 function ( pieces
) {
454 var $changesListContent
= pieces
.changes
,
455 $fieldset
= pieces
.fieldset
;
456 this.changesListModel
.update( $changesListContent
, $fieldset
);
458 // Do nothing for failure
463 * Update the model state from given the given parameters.
465 * This is an internal method, and should only be used from inside
468 * @param {Object} parameters Object representing the parameters for
469 * filters and highlights
471 mw
.rcfilters
.Controller
.prototype._updateModelState = function ( parameters
) {
472 // Update filter states
473 this.filtersModel
.toggleFiltersSelected(
474 this.filtersModel
.getFiltersFromParameters(
479 // Update highlight state
480 this.filtersModel
.toggleHighlight( !!parameters
.highlights
);
481 this.filtersModel
.getItems().forEach( function ( filterItem
) {
482 var color
= parameters
[ filterItem
.getName() + '_color' ];
484 filterItem
.setHighlightColor( color
);
486 filterItem
.clearHighlightColor();
490 // Check all filter interactions
491 this.filtersModel
.reassessFilterInteractions();
495 * Get an object representing the default parameter state, whether
496 * it is from the model defaults or from the saved queries.
498 * @return {Object} Default parameters
500 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
501 var data
, queryHighlights
,
503 savedHighlights
= {},
504 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
506 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
507 defaultSavedQueryItem
) {
509 data
= defaultSavedQueryItem
.getData();
511 queryHighlights
= data
.highlights
|| {};
512 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
514 // Translate highlights to parameters
515 savedHighlights
.highlights
= queryHighlights
.highlights
;
516 $.each( queryHighlights
, function ( filterName
, color
) {
517 if ( filterName
!== 'highlights' ) {
518 savedHighlights
[ filterName
+ '_color' ] = color
;
522 return $.extend( true, {}, savedParams
, savedHighlights
);
525 return this.filtersModel
.getDefaultParams();
529 * Update the URL of the page to reflect current filters
531 * This should not be called directly from outside the controller.
532 * If an action requires changing the URL, it should either use the
533 * highlighting actions below, or call #updateChangesList which does
534 * the uri corrections already.
536 * @param {Object} [params] Extra parameters to add to the API call
538 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
540 notEquivalent = function ( obj1
, obj2
) {
541 var keys
= Object
.keys( obj1
).concat( Object
.keys( obj2
) );
542 return keys
.some( function ( key
) {
543 return obj1
[ key
] != obj2
[ key
]; // eslint-disable-line eqeqeq
547 params
= params
|| {};
549 updatedUri
= this._getUpdatedUri();
550 updatedUri
.extend( params
);
552 if ( notEquivalent( updatedUri
.query
, new mw
.Uri().query
) ) {
553 window
.history
.pushState( { tag
: 'rcfilters' }, document
.title
, updatedUri
.toString() );
558 * Get an updated mw.Uri object based on the model state
560 * @return {mw.Uri} Updated Uri
562 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
563 var uri
= new mw
.Uri(),
564 highlightParams
= this.filtersModel
.getHighlightParameters();
566 // Add to existing queries in URL
567 // TODO: Clean up the list of filters; perhaps 'falsy' filters
568 // shouldn't appear at all? Or compare to existing query string
569 // and see if current state of a specific filter is needed?
570 uri
.extend( this.filtersModel
.getParametersFromFilters() );
573 Object
.keys( highlightParams
).forEach( function ( paramName
) {
574 if ( highlightParams
[ paramName
] ) {
575 uri
.query
[ paramName
] = highlightParams
[ paramName
];
577 delete uri
.query
[ paramName
];
585 * Fetch the list of changes from the server for the current filters
587 * @return {jQuery.Promise} Promise object that will resolve with the changes list
588 * or with a string denoting no results.
590 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
591 var uri
= this._getUpdatedUri(),
592 requestId
= ++this.requestCounter
,
593 latestRequest = function () {
594 return requestId
=== this.requestCounter
;
597 return $.ajax( uri
.toString(), { contentType
: 'html' } )
602 if ( !latestRequest() ) {
603 return $.Deferred().reject();
606 $parsed
= $( $.parseHTML( html
) );
610 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
612 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
616 function ( responseObj
) {
619 if ( !latestRequest() ) {
620 return $.Deferred().reject();
623 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
625 // Force a resolve state to this promise
626 return $.Deferred().resolve( {
627 changes
: 'NO_RESULTS',
628 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
635 * Track usage of highlight feature
637 * @param {string} action
638 * @param {array|object|string} filters
640 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
641 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
642 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
644 'event.ChangesListHighlights',
648 userId
: mw
.user
.getId()
653 }( mediaWiki
, jQuery
) );