95e11d59f3aa5af0ac1851e0a600167f1fe0abb3
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;
21 OO
.initClass( mw
.rcfilters
.Controller
);
24 * Initialize the filter and parameter states
26 * @param {Array} filterStructure Filter definition and structure for the model
27 * @param {Object} [namespaceStructure] Namespace definition
28 * @param {Object} [tagList] Tag definition
30 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
) {
31 var parsedSavedQueries
,
33 $changesList
= $( '.mw-changeslist' ).first().contents();
35 // Initialize the model
36 this.filtersModel
.initializeFilters( filterStructure
, namespaceStructure
, tagList
);
38 this._buildBaseFilterState();
40 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
45 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
47 parsedSavedQueries
= {};
50 // The queries are saved in a minimized state, so we need
51 // to send over the base state so the saved queries model
52 // can normalize them per each query item
53 this.savedQueriesModel
.initialize(
55 this._getBaseFilterState()
58 // Check whether we need to load defaults.
59 // We do this by checking whether the current URI query
60 // contains any parameters recognized by the system.
61 // If it does, we load the given state.
62 // If it doesn't, we have no values at all, and we assume
63 // the user loads the base-page and we load defaults.
64 // Defaults should only be applied on load (if necessary)
66 this.initializing
= true;
68 this.savedQueriesModel
.getDefault() &&
69 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
71 // We have defaults from a saved query.
72 // We will load them straight-forward (as if
73 // they were clicked in the menu) so we trigger
74 // a full ajax request and change of URL
75 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
77 // There are either recognized parameters in the URL
78 // or there are none, but there is also no default
79 // saved query (so defaults are from the backend)
80 // We want to update the state but not fetch results
82 this.updateStateFromUrl( false );
84 // Update the changes list with the existing data
85 // so it gets processed
86 this.changesListModel
.update(
87 $changesList
.length
? $changesList
: 'NO_RESULTS',
88 $( 'fieldset.rcoptions' ).first()
92 this.initializing
= false;
93 this.switchView( 'default' );
97 * Switch the view of the filters model
99 * @param {string} view Requested view
101 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
102 this.filtersModel
.switchView( view
);
106 * Reset to default filters
108 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
109 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
110 this.updateChangesList();
114 * Empty all selected filters
116 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
117 var highlightedFilterNames
= this.filtersModel
118 .getHighlightedItems()
119 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
121 this.filtersModel
.emptyAllFilters();
122 this.filtersModel
.clearAllHighlightColors();
123 // Check all filter interactions
124 this.filtersModel
.reassessFilterInteractions();
126 this.updateChangesList();
128 if ( highlightedFilterNames
) {
129 this._trackHighlight( 'clearAll', highlightedFilterNames
);
134 * Update the selected state of a filter
136 * @param {string} filterName Filter name
137 * @param {boolean} [isSelected] Filter selected state
139 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
140 var filterItem
= this.filtersModel
.getItemByName( filterName
);
143 // If no filter was found, break
147 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
149 if ( filterItem
.isSelected() !== isSelected
) {
150 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
152 this.updateChangesList();
154 // Check filter interactions
155 this.filtersModel
.reassessFilterInteractions( filterItem
);
160 * Clear both highlight and selection of a filter
162 * @param {string} filterName Name of the filter item
164 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
165 var filterItem
= this.filtersModel
.getItemByName( filterName
),
166 isHighlighted
= filterItem
.isHighlighted();
168 if ( filterItem
.isSelected() || isHighlighted
) {
169 this.filtersModel
.clearHighlightColor( filterName
);
170 this.filtersModel
.toggleFilterSelected( filterName
, false );
171 this.updateChangesList();
172 this.filtersModel
.reassessFilterInteractions( filterItem
);
175 if ( isHighlighted
) {
176 this._trackHighlight( 'clear', filterName
);
181 * Toggle the highlight feature on and off
183 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
184 this.filtersModel
.toggleHighlight();
187 if ( this.filtersModel
.isHighlightEnabled() ) {
188 mw
.hook( 'RcFilters.highlight.enable' ).fire();
193 * Toggle the namespaces inverted feature on and off
195 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
196 this.filtersModel
.toggleInvertedNamespaces();
197 this.updateChangesList();
201 * Set the highlight color for a filter item
203 * @param {string} filterName Name of the filter item
204 * @param {string} color Selected color
206 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
207 this.filtersModel
.setHighlightColor( filterName
, color
);
209 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
213 * Clear highlight for a filter item
215 * @param {string} filterName Name of the filter item
217 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
218 this.filtersModel
.clearHighlightColor( filterName
);
220 this._trackHighlight( 'clear', filterName
);
224 * Save the current model state as a saved query
226 * @param {string} [label] Label of the saved query
228 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
) {
229 var highlightedItems
= {},
230 highlightEnabled
= this.filtersModel
.isHighlightEnabled();
232 // Prepare highlights
233 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
234 highlightedItems
[ item
.getName() ] = highlightEnabled
?
235 item
.getHighlightColor() : null;
237 // These are filter states; highlight is stored as boolean
238 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
241 this.savedQueriesModel
.addNewQuery(
242 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
244 filters
: this.filtersModel
.getSelectedState(),
245 highlights
: highlightedItems
,
246 invert
: this.filtersModel
.areNamespacesInverted()
251 this._saveSavedQueries();
255 * Remove a saved query
257 * @param {string} queryID Query id
259 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
260 var query
= this.savedQueriesModel
.getItemByID( queryID
);
262 this.savedQueriesModel
.removeItems( [ query
] );
264 // Check if this item was the default
265 if ( this.savedQueriesModel
.getDefault() === queryID
) {
266 // Nulify the default
267 this.savedQueriesModel
.setDefault( null );
269 this._saveSavedQueries();
273 * Rename a saved query
275 * @param {string} queryID Query id
276 * @param {string} newLabel New label for the query
278 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
279 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
282 queryItem
.updateLabel( newLabel
);
284 this._saveSavedQueries();
288 * Set a saved query as default
290 * @param {string} queryID Query Id. If null is given, default
293 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
294 this.savedQueriesModel
.setDefault( queryID
);
295 this._saveSavedQueries();
301 * @param {string} queryID Query id
303 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
304 var data
, highlights
,
305 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
308 data
= queryItem
.getData();
309 highlights
= data
.highlights
;
311 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
312 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
314 // Update model state from filters
315 this.filtersModel
.toggleFiltersSelected( data
.filters
);
317 // Update namespace inverted property
318 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
320 // Update highlight state
321 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
322 this.filtersModel
.getItems().forEach( function ( filterItem
) {
323 var color
= highlights
[ filterItem
.getName() ];
325 filterItem
.setHighlightColor( color
);
327 filterItem
.clearHighlightColor();
331 // Check all filter interactions
332 this.filtersModel
.reassessFilterInteractions();
334 this.updateChangesList();
339 * Check whether the current filter and highlight state exists
340 * in the saved queries model.
342 * @return {boolean} Query exists
344 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
345 var highlightedItems
= {};
347 // Prepare highlights of the current query
348 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
349 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
351 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
353 return this.savedQueriesModel
.findMatchingQuery(
355 filters
: this.filtersModel
.getSelectedState(),
356 highlights
: highlightedItems
,
357 invert
: this.filtersModel
.areNamespacesInverted()
363 * Get an object representing the base state of parameters
366 * This is meant to make sure that the saved queries that are
367 * in memory are always the same structure as what we would get
368 * by calling the current model's "getSelectedState" and by checking
371 * In cases where a user saved a query when the system had a certain
372 * set of filters, and then a filter was added to the system, we want
373 * to make sure that the stored queries can still be comparable to
374 * the current state, which means that we need the base state for
377 * - Saved queries are stored in "minimal" view (only changed filters
378 * are stored); When we initialize the system, we merge each minimal
379 * query with the base state (using 'getNormalizedFilters') so all
380 * saved queries have the exact same structure as what we would get
381 * by checking the getSelectedState of the filter.
382 * - When we save the queries, we minimize the object to only represent
383 * whatever has actually changed, rather than store the entire
384 * object. To check what actually is different so we can store it,
385 * we need to obtain a base state to compare against, this is
386 * what #_getMinimalFilterList does
388 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
389 var defaultParams
= this.filtersModel
.getDefaultParams(),
390 highlightedItems
= {};
392 // Prepare highlights
393 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
394 highlightedItems
[ item
.getName() ] = null;
396 highlightedItems
.highlight
= false;
398 this.baseFilterState
= {
399 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
400 highlights
: highlightedItems
,
406 * Get an object representing the base filter state of both
407 * filters and highlights. The structure is similar to what we use
408 * to store each query in the saved queries object:
414 * filterName: (string|null)
418 * @return {Object} Object representing the base state of
419 * parameters and highlights
421 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
422 return this.baseFilterState
;
426 * Get an object that holds only the parameters and highlights that have
427 * values different than the base default value.
429 * This is the reverse of the normalization we do initially on loading and
430 * initializing the saved queries model.
432 * @param {Object} valuesObject Object representing the state of both
433 * filters and highlights in its normalized version, to be minimized.
434 * @return {Object} Minimal filters and highlights list
436 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
437 var result
= { filters
: {}, highlights
: {} },
438 baseState
= this._getBaseFilterState();
441 $.each( valuesObject
.filters
, function ( name
, value
) {
442 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
443 result
.filters
[ name
] = value
;
447 $.each( valuesObject
.highlights
, function ( name
, value
) {
448 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
449 result
.highlights
[ name
] = value
;
457 * Save the current state of the saved queries model with all
458 * query item representation in the user settings.
460 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
462 state
= this.savedQueriesModel
.getState(),
465 // Minimize before save
466 $.each( state
.queries
, function ( queryID
, info
) {
467 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
471 stringified
= JSON
.stringify( state
);
473 if ( stringified
.length
> 65535 ) {
474 // Sanity check, since the preference can only hold that.
478 // Save the preference
479 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
480 // Update the preference for this session
481 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
485 * Synchronize the URL with the current state of the filters
486 * without adding an history entry.
488 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
489 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
493 * Update filter state (selection and highlighting) based
494 * on current URL values.
496 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
497 * list based on the updated model.
499 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
500 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
502 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
504 // Only update and fetch new results if it is requested
505 if ( fetchChangesList
) {
506 this.updateChangesList();
511 * Update the list of changes and notify the model
513 * @param {Object} [params] Extra parameters to add to the API call
515 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
) {
516 this._updateURL( params
);
517 this.changesListModel
.invalidate();
518 this._fetchChangesList()
521 function ( pieces
) {
522 var $changesListContent
= pieces
.changes
,
523 $fieldset
= pieces
.fieldset
;
524 this.changesListModel
.update( $changesListContent
, $fieldset
);
526 // Do nothing for failure
531 * Get an object representing the default parameter state, whether
532 * it is from the model defaults or from the saved queries.
534 * @return {Object} Default parameters
536 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
537 var data
, queryHighlights
,
539 savedHighlights
= {},
540 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
542 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
543 defaultSavedQueryItem
) {
545 data
= defaultSavedQueryItem
.getData();
547 queryHighlights
= data
.highlights
|| {};
548 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
550 // Translate highlights to parameters
551 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
552 $.each( queryHighlights
, function ( filterName
, color
) {
553 if ( filterName
!== 'highlights' ) {
554 savedHighlights
[ filterName
+ '_color' ] = color
;
558 return $.extend( true, {}, savedParams
, savedHighlights
, { invert
: data
.invert
} );
563 this.filtersModel
.getDefaultParams()
568 * Get an object representing the default parameter state, whether
569 * it is from the model defaults or from the saved queries.
571 * @return {Object} Default parameters
573 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
574 var data
, queryHighlights
,
576 savedHighlights
= {},
577 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
579 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
580 defaultSavedQueryItem
) {
582 data
= defaultSavedQueryItem
.getData();
584 queryHighlights
= data
.highlights
|| {};
585 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
587 // Translate highlights to parameters
588 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
589 $.each( queryHighlights
, function ( filterName
, color
) {
590 if ( filterName
!== 'highlights' ) {
591 savedHighlights
[ filterName
+ '_color' ] = color
;
595 return $.extend( true, {}, savedParams
, savedHighlights
);
598 return this.filtersModel
.getDefaultParams();
602 * Update the URL of the page to reflect current filters
604 * This should not be called directly from outside the controller.
605 * If an action requires changing the URL, it should either use the
606 * highlighting actions below, or call #updateChangesList which does
607 * the uri corrections already.
609 * @param {Object} [params] Extra parameters to add to the API call
611 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
612 var currentUri
= new mw
.Uri(),
613 updatedUri
= this._getUpdatedUri();
615 updatedUri
.extend( params
|| {} );
618 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
619 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
621 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
626 * Get an updated mw.Uri object based on the model state
628 * @return {mw.Uri} Updated Uri
630 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
631 var uri
= new mw
.Uri();
634 uri
.query
= this.uriProcessor
.minimizeQuery(
638 // We want to retain unrecognized params
639 // The uri params from model will override
640 // any recognized value in the current uri
641 // query, retain unrecognized params, and
642 // the result will then be minimized
644 this.uriProcessor
.getUriParametersFromModel(),
653 * Fetch the list of changes from the server for the current filters
655 * @return {jQuery.Promise} Promise object that will resolve with the changes list
656 * or with a string denoting no results.
658 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
659 var uri
= this._getUpdatedUri(),
660 requestId
= ++this.requestCounter
,
661 latestRequest = function () {
662 return requestId
=== this.requestCounter
;
665 return $.ajax( uri
.toString(), { contentType
: 'html' } )
670 if ( !latestRequest() ) {
671 return $.Deferred().reject();
674 $parsed
= $( $.parseHTML( html
) );
678 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
680 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
684 function ( responseObj
) {
687 if ( !latestRequest() ) {
688 return $.Deferred().reject();
691 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
693 // Force a resolve state to this promise
694 return $.Deferred().resolve( {
695 changes
: 'NO_RESULTS',
696 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
703 * Track usage of highlight feature
705 * @param {string} action
706 * @param {array|object|string} filters
708 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
709 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
710 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
712 'event.ChangesListHighlights',
716 userId
: mw
.user
.getId()
721 }( mediaWiki
, jQuery
) );