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
,
35 $changesList
= $( '.mw-changeslist' ).first().contents();
38 if ( namespaceStructure
) {
40 $.each( namespaceStructure
, function ( namespaceID
, label
) {
41 // Build and clean up the individual namespace items definition
44 label
: label
|| mw
.msg( 'blanknamespace' ),
47 ( namespaceID
< 0 || namespaceID
% 2 === 0 ) ?
50 cssClass
: 'mw-changeslist-ns-' + namespaceID
55 title
: mw
.msg( 'namespaces' ),
58 // Group definition (single group)
61 type
: 'string_options',
62 title
: mw
.msg( 'namespaces' ),
63 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
79 type
: 'string_options',
80 title
: 'rcfilters-view-tags', // Message key
81 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
90 // Initialize the model
91 this.filtersModel
.initializeFilters( filterStructure
, views
);
93 this._buildBaseFilterState();
95 this.uriProcessor
= new mw
.rcfilters
.UriProcessor(
100 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
102 parsedSavedQueries
= {};
105 // The queries are saved in a minimized state, so we need
106 // to send over the base state so the saved queries model
107 // can normalize them per each query item
108 this.savedQueriesModel
.initialize(
110 this._getBaseFilterState()
113 // Check whether we need to load defaults.
114 // We do this by checking whether the current URI query
115 // contains any parameters recognized by the system.
116 // If it does, we load the given state.
117 // If it doesn't, we have no values at all, and we assume
118 // the user loads the base-page and we load defaults.
119 // Defaults should only be applied on load (if necessary)
121 this.initializing
= true;
123 this.savedQueriesModel
.getDefault() &&
124 !this.uriProcessor
.doesQueryContainRecognizedParams( uri
.query
)
126 // We have defaults from a saved query.
127 // We will load them straight-forward (as if
128 // they were clicked in the menu) so we trigger
129 // a full ajax request and change of URL
130 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
132 // There are either recognized parameters in the URL
133 // or there are none, but there is also no default
134 // saved query (so defaults are from the backend)
135 // We want to update the state but not fetch results
137 this.updateStateFromUrl( false );
139 // Update the changes list with the existing data
140 // so it gets processed
141 this.changesListModel
.update(
142 $changesList
.length
? $changesList
: 'NO_RESULTS',
143 $( 'fieldset.rcoptions' ).first()
147 this.initializing
= false;
148 this.switchView( 'default' );
152 * Switch the view of the filters model
154 * @param {string} view Requested view
156 mw
.rcfilters
.Controller
.prototype.switchView = function ( view
) {
157 this.filtersModel
.switchView( view
);
161 * Reset to default filters
163 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
164 this.uriProcessor
.updateModelBasedOnQuery( this._getDefaultParams() );
165 this.updateChangesList();
169 * Empty all selected filters
171 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
172 var highlightedFilterNames
= this.filtersModel
173 .getHighlightedItems()
174 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
176 this.filtersModel
.emptyAllFilters();
177 this.filtersModel
.clearAllHighlightColors();
178 // Check all filter interactions
179 this.filtersModel
.reassessFilterInteractions();
181 this.updateChangesList();
183 if ( highlightedFilterNames
) {
184 this._trackHighlight( 'clearAll', highlightedFilterNames
);
189 * Update the selected state of a filter
191 * @param {string} filterName Filter name
192 * @param {boolean} [isSelected] Filter selected state
194 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
195 var filterItem
= this.filtersModel
.getItemByName( filterName
);
198 // If no filter was found, break
202 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
204 if ( filterItem
.isSelected() !== isSelected
) {
205 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
207 this.updateChangesList();
209 // Check filter interactions
210 this.filtersModel
.reassessFilterInteractions( filterItem
);
215 * Clear both highlight and selection of a filter
217 * @param {string} filterName Name of the filter item
219 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
220 var filterItem
= this.filtersModel
.getItemByName( filterName
),
221 isHighlighted
= filterItem
.isHighlighted();
223 if ( filterItem
.isSelected() || isHighlighted
) {
224 this.filtersModel
.clearHighlightColor( filterName
);
225 this.filtersModel
.toggleFilterSelected( filterName
, false );
226 this.updateChangesList();
227 this.filtersModel
.reassessFilterInteractions( filterItem
);
230 if ( isHighlighted
) {
231 this._trackHighlight( 'clear', filterName
);
236 * Toggle the highlight feature on and off
238 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
239 this.filtersModel
.toggleHighlight();
242 if ( this.filtersModel
.isHighlightEnabled() ) {
243 mw
.hook( 'RcFilters.highlight.enable' ).fire();
248 * Toggle the namespaces inverted feature on and off
250 mw
.rcfilters
.Controller
.prototype.toggleInvertedNamespaces = function () {
251 this.filtersModel
.toggleInvertedNamespaces();
252 this.updateChangesList();
256 * Set the highlight color for a filter item
258 * @param {string} filterName Name of the filter item
259 * @param {string} color Selected color
261 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
262 this.filtersModel
.setHighlightColor( filterName
, color
);
264 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
268 * Clear highlight for a filter item
270 * @param {string} filterName Name of the filter item
272 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
273 this.filtersModel
.clearHighlightColor( filterName
);
275 this._trackHighlight( 'clear', filterName
);
279 * Save the current model state as a saved query
281 * @param {string} [label] Label of the saved query
283 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
) {
284 var highlightedItems
= {},
285 highlightEnabled
= this.filtersModel
.isHighlightEnabled();
287 // Prepare highlights
288 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
289 highlightedItems
[ item
.getName() ] = highlightEnabled
?
290 item
.getHighlightColor() : null;
292 // These are filter states; highlight is stored as boolean
293 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
296 this.savedQueriesModel
.addNewQuery(
297 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
299 filters
: this.filtersModel
.getSelectedState(),
300 highlights
: highlightedItems
,
301 invert
: this.filtersModel
.areNamespacesInverted()
306 this._saveSavedQueries();
310 * Remove a saved query
312 * @param {string} queryID Query id
314 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
315 this.savedQueriesModel
.removeQuery( queryID
);
317 this._saveSavedQueries();
321 * Rename a saved query
323 * @param {string} queryID Query id
324 * @param {string} newLabel New label for the query
326 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
327 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
330 queryItem
.updateLabel( newLabel
);
332 this._saveSavedQueries();
336 * Set a saved query as default
338 * @param {string} queryID Query Id. If null is given, default
341 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
342 this.savedQueriesModel
.setDefault( queryID
);
343 this._saveSavedQueries();
349 * @param {string} queryID Query id
351 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
352 var data
, highlights
,
353 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
356 data
= queryItem
.getData();
357 highlights
= data
.highlights
;
359 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
360 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
362 // Update model state from filters
363 this.filtersModel
.toggleFiltersSelected( data
.filters
);
365 // Update namespace inverted property
366 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
368 // Update highlight state
369 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
370 this.filtersModel
.getItems().forEach( function ( filterItem
) {
371 var color
= highlights
[ filterItem
.getName() ];
373 filterItem
.setHighlightColor( color
);
375 filterItem
.clearHighlightColor();
379 // Check all filter interactions
380 this.filtersModel
.reassessFilterInteractions();
382 this.updateChangesList();
387 * Check whether the current filter and highlight state exists
388 * in the saved queries model.
390 * @return {boolean} Query exists
392 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
393 var highlightedItems
= {};
395 // Prepare highlights of the current query
396 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
397 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
399 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
401 return this.savedQueriesModel
.findMatchingQuery(
403 filters
: this.filtersModel
.getSelectedState(),
404 highlights
: highlightedItems
,
405 invert
: this.filtersModel
.areNamespacesInverted()
411 * Get an object representing the base state of parameters
414 * This is meant to make sure that the saved queries that are
415 * in memory are always the same structure as what we would get
416 * by calling the current model's "getSelectedState" and by checking
419 * In cases where a user saved a query when the system had a certain
420 * set of filters, and then a filter was added to the system, we want
421 * to make sure that the stored queries can still be comparable to
422 * the current state, which means that we need the base state for
425 * - Saved queries are stored in "minimal" view (only changed filters
426 * are stored); When we initialize the system, we merge each minimal
427 * query with the base state (using 'getNormalizedFilters') so all
428 * saved queries have the exact same structure as what we would get
429 * by checking the getSelectedState of the filter.
430 * - When we save the queries, we minimize the object to only represent
431 * whatever has actually changed, rather than store the entire
432 * object. To check what actually is different so we can store it,
433 * we need to obtain a base state to compare against, this is
434 * what #_getMinimalFilterList does
436 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
437 var defaultParams
= this.filtersModel
.getDefaultParams(),
438 highlightedItems
= {};
440 // Prepare highlights
441 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
442 highlightedItems
[ item
.getName() ] = null;
444 highlightedItems
.highlight
= false;
446 this.baseFilterState
= {
447 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
448 highlights
: highlightedItems
,
454 * Get an object representing the base filter state of both
455 * filters and highlights. The structure is similar to what we use
456 * to store each query in the saved queries object:
462 * filterName: (string|null)
466 * @return {Object} Object representing the base state of
467 * parameters and highlights
469 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
470 return this.baseFilterState
;
474 * Get an object that holds only the parameters and highlights that have
475 * values different than the base default value.
477 * This is the reverse of the normalization we do initially on loading and
478 * initializing the saved queries model.
480 * @param {Object} valuesObject Object representing the state of both
481 * filters and highlights in its normalized version, to be minimized.
482 * @return {Object} Minimal filters and highlights list
484 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
485 var result
= { filters
: {}, highlights
: {} },
486 baseState
= this._getBaseFilterState();
489 $.each( valuesObject
.filters
, function ( name
, value
) {
490 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
491 result
.filters
[ name
] = value
;
495 $.each( valuesObject
.highlights
, function ( name
, value
) {
496 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
497 result
.highlights
[ name
] = value
;
505 * Save the current state of the saved queries model with all
506 * query item representation in the user settings.
508 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
510 state
= this.savedQueriesModel
.getState(),
513 // Minimize before save
514 $.each( state
.queries
, function ( queryID
, info
) {
515 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
519 stringified
= JSON
.stringify( state
);
521 if ( stringified
.length
> 65535 ) {
522 // Sanity check, since the preference can only hold that.
526 // Save the preference
527 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
528 // Update the preference for this session
529 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
533 * Synchronize the URL with the current state of the filters
534 * without adding an history entry.
536 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
537 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
541 * Update filter state (selection and highlighting) based
542 * on current URL values.
544 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
545 * list based on the updated model.
547 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
548 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
550 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
552 // Only update and fetch new results if it is requested
553 if ( fetchChangesList
) {
554 this.updateChangesList();
559 * Update the list of changes and notify the model
561 * @param {Object} [params] Extra parameters to add to the API call
563 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
) {
564 this._updateURL( params
);
565 this.changesListModel
.invalidate();
566 this._fetchChangesList()
569 function ( pieces
) {
570 var $changesListContent
= pieces
.changes
,
571 $fieldset
= pieces
.fieldset
;
572 this.changesListModel
.update( $changesListContent
, $fieldset
);
574 // Do nothing for failure
579 * Get an object representing the default parameter state, whether
580 * it is from the model defaults or from the saved queries.
582 * @return {Object} Default parameters
584 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
585 var data
, queryHighlights
,
587 savedHighlights
= {},
588 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
590 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
591 defaultSavedQueryItem
) {
593 data
= defaultSavedQueryItem
.getData();
595 queryHighlights
= data
.highlights
|| {};
596 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
598 // Translate highlights to parameters
599 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
600 $.each( queryHighlights
, function ( filterName
, color
) {
601 if ( filterName
!== 'highlights' ) {
602 savedHighlights
[ filterName
+ '_color' ] = color
;
606 return $.extend( true, {}, savedParams
, savedHighlights
, { invert
: data
.invert
} );
611 this.filtersModel
.getDefaultParams()
616 * Get an object representing the default parameter state, whether
617 * it is from the model defaults or from the saved queries.
619 * @return {Object} Default parameters
621 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
622 var data
, queryHighlights
,
624 savedHighlights
= {},
625 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
627 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
628 defaultSavedQueryItem
) {
630 data
= defaultSavedQueryItem
.getData();
632 queryHighlights
= data
.highlights
|| {};
633 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
635 // Translate highlights to parameters
636 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
637 $.each( queryHighlights
, function ( filterName
, color
) {
638 if ( filterName
!== 'highlights' ) {
639 savedHighlights
[ filterName
+ '_color' ] = color
;
643 return $.extend( true, {}, savedParams
, savedHighlights
);
646 return this.filtersModel
.getDefaultParams();
650 * Update the URL of the page to reflect current filters
652 * This should not be called directly from outside the controller.
653 * If an action requires changing the URL, it should either use the
654 * highlighting actions below, or call #updateChangesList which does
655 * the uri corrections already.
657 * @param {Object} [params] Extra parameters to add to the API call
659 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
660 var currentUri
= new mw
.Uri(),
661 updatedUri
= this._getUpdatedUri();
663 updatedUri
.extend( params
|| {} );
666 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
667 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
669 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
674 * Get an updated mw.Uri object based on the model state
676 * @return {mw.Uri} Updated Uri
678 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
679 var uri
= new mw
.Uri();
682 uri
.query
= this.uriProcessor
.minimizeQuery(
686 // We want to retain unrecognized params
687 // The uri params from model will override
688 // any recognized value in the current uri
689 // query, retain unrecognized params, and
690 // the result will then be minimized
692 this.uriProcessor
.getUriParametersFromModel(),
701 * Fetch the list of changes from the server for the current filters
703 * @return {jQuery.Promise} Promise object that will resolve with the changes list
704 * or with a string denoting no results.
706 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
707 var uri
= this._getUpdatedUri(),
708 requestId
= ++this.requestCounter
,
709 latestRequest = function () {
710 return requestId
=== this.requestCounter
;
713 return $.ajax( uri
.toString(), { contentType
: 'html' } )
718 if ( !latestRequest() ) {
719 return $.Deferred().reject();
722 $parsed
= $( $.parseHTML( html
) );
726 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
728 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
732 function ( responseObj
) {
735 if ( !latestRequest() ) {
736 return $.Deferred().reject();
739 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
741 // Force a resolve state to this promise
742 return $.Deferred().resolve( {
743 changes
: 'NO_RESULTS',
744 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
751 * Track usage of highlight feature
753 * @param {string} action
754 * @param {array|object|string} filters
756 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
757 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
758 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
760 'event.ChangesListHighlights',
764 userId
: mw
.user
.getId()
769 }( mediaWiki
, jQuery
) );