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 var query
= this.savedQueriesModel
.getItemByID( queryID
);
317 this.savedQueriesModel
.removeItems( [ query
] );
319 // Check if this item was the default
320 if ( this.savedQueriesModel
.getDefault() === queryID
) {
321 // Nulify the default
322 this.savedQueriesModel
.setDefault( null );
324 this._saveSavedQueries();
328 * Rename a saved query
330 * @param {string} queryID Query id
331 * @param {string} newLabel New label for the query
333 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
334 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
337 queryItem
.updateLabel( newLabel
);
339 this._saveSavedQueries();
343 * Set a saved query as default
345 * @param {string} queryID Query Id. If null is given, default
348 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
349 this.savedQueriesModel
.setDefault( queryID
);
350 this._saveSavedQueries();
356 * @param {string} queryID Query id
358 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
359 var data
, highlights
,
360 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
363 data
= queryItem
.getData();
364 highlights
= data
.highlights
;
366 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
367 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
369 // Update model state from filters
370 this.filtersModel
.toggleFiltersSelected( data
.filters
);
372 // Update namespace inverted property
373 this.filtersModel
.toggleInvertedNamespaces( !!Number( data
.invert
) );
375 // Update highlight state
376 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
377 this.filtersModel
.getItems().forEach( function ( filterItem
) {
378 var color
= highlights
[ filterItem
.getName() ];
380 filterItem
.setHighlightColor( color
);
382 filterItem
.clearHighlightColor();
386 // Check all filter interactions
387 this.filtersModel
.reassessFilterInteractions();
389 this.updateChangesList();
394 * Check whether the current filter and highlight state exists
395 * in the saved queries model.
397 * @return {boolean} Query exists
399 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
400 var highlightedItems
= {};
402 // Prepare highlights of the current query
403 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
404 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
406 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
408 return this.savedQueriesModel
.findMatchingQuery(
410 filters
: this.filtersModel
.getSelectedState(),
411 highlights
: highlightedItems
,
412 invert
: this.filtersModel
.areNamespacesInverted()
418 * Get an object representing the base state of parameters
421 * This is meant to make sure that the saved queries that are
422 * in memory are always the same structure as what we would get
423 * by calling the current model's "getSelectedState" and by checking
426 * In cases where a user saved a query when the system had a certain
427 * set of filters, and then a filter was added to the system, we want
428 * to make sure that the stored queries can still be comparable to
429 * the current state, which means that we need the base state for
432 * - Saved queries are stored in "minimal" view (only changed filters
433 * are stored); When we initialize the system, we merge each minimal
434 * query with the base state (using 'getNormalizedFilters') so all
435 * saved queries have the exact same structure as what we would get
436 * by checking the getSelectedState of the filter.
437 * - When we save the queries, we minimize the object to only represent
438 * whatever has actually changed, rather than store the entire
439 * object. To check what actually is different so we can store it,
440 * we need to obtain a base state to compare against, this is
441 * what #_getMinimalFilterList does
443 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
444 var defaultParams
= this.filtersModel
.getDefaultParams(),
445 highlightedItems
= {};
447 // Prepare highlights
448 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
449 highlightedItems
[ item
.getName() ] = null;
451 highlightedItems
.highlight
= false;
453 this.baseFilterState
= {
454 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
455 highlights
: highlightedItems
,
461 * Get an object representing the base filter state of both
462 * filters and highlights. The structure is similar to what we use
463 * to store each query in the saved queries object:
469 * filterName: (string|null)
473 * @return {Object} Object representing the base state of
474 * parameters and highlights
476 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
477 return this.baseFilterState
;
481 * Get an object that holds only the parameters and highlights that have
482 * values different than the base default value.
484 * This is the reverse of the normalization we do initially on loading and
485 * initializing the saved queries model.
487 * @param {Object} valuesObject Object representing the state of both
488 * filters and highlights in its normalized version, to be minimized.
489 * @return {Object} Minimal filters and highlights list
491 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
492 var result
= { filters
: {}, highlights
: {} },
493 baseState
= this._getBaseFilterState();
496 $.each( valuesObject
.filters
, function ( name
, value
) {
497 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
498 result
.filters
[ name
] = value
;
502 $.each( valuesObject
.highlights
, function ( name
, value
) {
503 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
504 result
.highlights
[ name
] = value
;
512 * Save the current state of the saved queries model with all
513 * query item representation in the user settings.
515 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
517 state
= this.savedQueriesModel
.getState(),
520 // Minimize before save
521 $.each( state
.queries
, function ( queryID
, info
) {
522 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
526 stringified
= JSON
.stringify( state
);
528 if ( stringified
.length
> 65535 ) {
529 // Sanity check, since the preference can only hold that.
533 // Save the preference
534 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
535 // Update the preference for this session
536 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
540 * Synchronize the URL with the current state of the filters
541 * without adding an history entry.
543 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
544 mw
.rcfilters
.UriProcessor
.static.replaceState( this._getUpdatedUri() );
548 * Update filter state (selection and highlighting) based
549 * on current URL values.
551 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
552 * list based on the updated model.
554 mw
.rcfilters
.Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
555 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
557 this.uriProcessor
.updateModelBasedOnQuery( new mw
.Uri().query
);
559 // Only update and fetch new results if it is requested
560 if ( fetchChangesList
) {
561 this.updateChangesList();
566 * Update the list of changes and notify the model
568 * @param {Object} [params] Extra parameters to add to the API call
570 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
) {
571 this._updateURL( params
);
572 this.changesListModel
.invalidate();
573 this._fetchChangesList()
576 function ( pieces
) {
577 var $changesListContent
= pieces
.changes
,
578 $fieldset
= pieces
.fieldset
;
579 this.changesListModel
.update( $changesListContent
, $fieldset
);
581 // Do nothing for failure
586 * Get an object representing the default parameter state, whether
587 * it is from the model defaults or from the saved queries.
589 * @return {Object} Default parameters
591 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
592 var data
, queryHighlights
,
594 savedHighlights
= {},
595 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
597 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
598 defaultSavedQueryItem
) {
600 data
= defaultSavedQueryItem
.getData();
602 queryHighlights
= data
.highlights
|| {};
603 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
605 // Translate highlights to parameters
606 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
607 $.each( queryHighlights
, function ( filterName
, color
) {
608 if ( filterName
!== 'highlights' ) {
609 savedHighlights
[ filterName
+ '_color' ] = color
;
613 return $.extend( true, {}, savedParams
, savedHighlights
, { invert
: data
.invert
} );
618 this.filtersModel
.getDefaultParams()
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
);
653 return this.filtersModel
.getDefaultParams();
657 * Update the URL of the page to reflect current filters
659 * This should not be called directly from outside the controller.
660 * If an action requires changing the URL, it should either use the
661 * highlighting actions below, or call #updateChangesList which does
662 * the uri corrections already.
664 * @param {Object} [params] Extra parameters to add to the API call
666 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
667 var currentUri
= new mw
.Uri(),
668 updatedUri
= this._getUpdatedUri();
670 updatedUri
.extend( params
|| {} );
673 this.uriProcessor
.getVersion( currentUri
.query
) !== 2 ||
674 this.uriProcessor
.isNewState( currentUri
.query
, updatedUri
.query
)
676 mw
.rcfilters
.UriProcessor
.static.replaceState( updatedUri
);
681 * Get an updated mw.Uri object based on the model state
683 * @return {mw.Uri} Updated Uri
685 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
686 var uri
= new mw
.Uri();
689 uri
.query
= this.uriProcessor
.minimizeQuery(
693 // We want to retain unrecognized params
694 // The uri params from model will override
695 // any recognized value in the current uri
696 // query, retain unrecognized params, and
697 // the result will then be minimized
699 this.uriProcessor
.getUriParametersFromModel(),
708 * Fetch the list of changes from the server for the current filters
710 * @return {jQuery.Promise} Promise object that will resolve with the changes list
711 * or with a string denoting no results.
713 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
714 var uri
= this._getUpdatedUri(),
715 requestId
= ++this.requestCounter
,
716 latestRequest = function () {
717 return requestId
=== this.requestCounter
;
720 return $.ajax( uri
.toString(), { contentType
: 'html' } )
725 if ( !latestRequest() ) {
726 return $.Deferred().reject();
729 $parsed
= $( $.parseHTML( html
) );
733 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
735 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
739 function ( responseObj
) {
742 if ( !latestRequest() ) {
743 return $.Deferred().reject();
746 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
748 // Force a resolve state to this promise
749 return $.Deferred().resolve( {
750 changes
: 'NO_RESULTS',
751 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
758 * Track usage of highlight feature
760 * @param {string} action
761 * @param {array|object|string} filters
763 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
764 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
765 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
767 'event.ChangesListHighlights',
771 userId
: mw
.user
.getId()
776 }( mediaWiki
, jQuery
) );