b7b46f6748a048dac7e1738c6e178dac5ae09529
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.emptyParameterState
= {};
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
28 mw
.rcfilters
.Controller
.prototype.initialize = function ( filterStructure
) {
29 var parsedSavedQueries
, validParameterNames
,
31 $changesList
= $( '.mw-changeslist' ).first().contents();
33 // Initialize the model
34 this.filtersModel
.initializeFilters( filterStructure
);
36 this._buildBaseFilterState();
37 this._buildEmptyParameterState();
38 validParameterNames
= Object
.keys( this._getEmptyParameterState() )
39 .filter( function ( param
) {
40 // Remove 'highlight' parameter from this check;
41 // if it's the only parameter in the URL we still
42 // want to consider the URL 'empty' for defaults to load
43 return param
!== 'highlight';
47 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( 'rcfilters-saved-queries' ) || '{}' );
49 parsedSavedQueries
= {};
52 // The queries are saved in a minimized state, so we need
53 // to send over the base state so the saved queries model
54 // can normalize them per each query item
55 this.savedQueriesModel
.initialize(
57 this._getBaseFilterState()
60 // Check whether we need to load defaults.
61 // We do this by checking whether the current URI query
62 // contains any parameters recognized by the system.
63 // If it does, we load the given state.
64 // If it doesn't, we have no values at all, and we assume
65 // the user loads the base-page and we load defaults.
66 // Defaults should only be applied on load (if necessary)
69 Object
.keys( uri
.query
).some( function ( parameter
) {
70 return validParameterNames
.indexOf( parameter
) > -1;
73 // There are parameters in the url, update model state
74 this.updateStateBasedOnUrl();
76 this.initializing
= true;
77 // No valid parameters are given, load defaults
78 this._updateModelState(
81 // We've ignored the highlight parameter for the sake
82 // of seeing whether we need to apply defaults - but
83 // while we do load the defaults, we still want to retain
84 // the actual value given in the URL for it on top of the
86 { highlight
: String( Number( uri
.query
.highlight
) ) },
87 this._getDefaultParams()
90 this.updateChangesList();
91 this.initializing
= false;
94 // Update the changes list with the existing data
95 // so it gets processed
96 this.changesListModel
.update(
97 $changesList
.length
? $changesList
: 'NO_RESULTS',
98 $( 'fieldset.rcoptions' ).first()
103 * Reset to default filters
105 mw
.rcfilters
.Controller
.prototype.resetToDefaults = function () {
106 this._updateModelState( $.extend( true, { highlight
: '0' }, this._getDefaultParams() ) );
107 this.updateChangesList();
111 * Empty all selected filters
113 mw
.rcfilters
.Controller
.prototype.emptyFilters = function () {
114 var highlightedFilterNames
= this.filtersModel
115 .getHighlightedItems()
116 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
118 this.filtersModel
.emptyAllFilters();
119 this.filtersModel
.clearAllHighlightColors();
120 // Check all filter interactions
121 this.filtersModel
.reassessFilterInteractions();
123 this.updateChangesList();
125 if ( highlightedFilterNames
) {
126 this._trackHighlight( 'clearAll', highlightedFilterNames
);
131 * Update the selected state of a filter
133 * @param {string} filterName Filter name
134 * @param {boolean} [isSelected] Filter selected state
136 mw
.rcfilters
.Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
137 var filterItem
= this.filtersModel
.getItemByName( filterName
);
140 // If no filter was found, break
144 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
146 if ( filterItem
.isSelected() !== isSelected
) {
147 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
149 this.updateChangesList();
151 // Check filter interactions
152 this.filtersModel
.reassessFilterInteractions( filterItem
);
157 * Clear both highlight and selection of a filter
159 * @param {string} filterName Name of the filter item
161 mw
.rcfilters
.Controller
.prototype.clearFilter = function ( filterName
) {
162 var filterItem
= this.filtersModel
.getItemByName( filterName
),
163 isHighlighted
= filterItem
.isHighlighted();
165 if ( filterItem
.isSelected() || isHighlighted
) {
166 this.filtersModel
.clearHighlightColor( filterName
);
167 this.filtersModel
.toggleFilterSelected( filterName
, false );
168 this.updateChangesList();
169 this.filtersModel
.reassessFilterInteractions( filterItem
);
172 if ( isHighlighted
) {
173 this._trackHighlight( 'clear', filterName
);
178 * Toggle the highlight feature on and off
180 mw
.rcfilters
.Controller
.prototype.toggleHighlight = function () {
181 this.filtersModel
.toggleHighlight();
184 if ( this.filtersModel
.isHighlightEnabled() ) {
185 mw
.hook( 'RcFilters.highlight.enable' ).fire();
190 * Set the highlight color for a filter item
192 * @param {string} filterName Name of the filter item
193 * @param {string} color Selected color
195 mw
.rcfilters
.Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
196 this.filtersModel
.setHighlightColor( filterName
, color
);
198 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
202 * Clear highlight for a filter item
204 * @param {string} filterName Name of the filter item
206 mw
.rcfilters
.Controller
.prototype.clearHighlightColor = function ( filterName
) {
207 this.filtersModel
.clearHighlightColor( filterName
);
209 this._trackHighlight( 'clear', filterName
);
213 * Save the current model state as a saved query
215 * @param {string} [label] Label of the saved query
217 mw
.rcfilters
.Controller
.prototype.saveCurrentQuery = function ( label
) {
218 var highlightedItems
= {},
219 highlightEnabled
= this.filtersModel
.isHighlightEnabled();
221 // Prepare highlights
222 this.filtersModel
.getHighlightedItems().forEach( function ( item
) {
223 highlightedItems
[ item
.getName() ] = highlightEnabled
?
224 item
.getHighlightColor() : null;
226 // These are filter states; highlight is stored as boolean
227 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
230 this.savedQueriesModel
.addNewQuery(
231 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
233 filters
: this.filtersModel
.getSelectedState(),
234 highlights
: highlightedItems
239 this._saveSavedQueries();
243 * Remove a saved query
245 * @param {string} queryID Query id
247 mw
.rcfilters
.Controller
.prototype.removeSavedQuery = function ( queryID
) {
248 var query
= this.savedQueriesModel
.getItemByID( queryID
);
250 this.savedQueriesModel
.removeItems( [ query
] );
252 // Check if this item was the default
253 if ( this.savedQueriesModel
.getDefault() === queryID
) {
254 // Nulify the default
255 this.savedQueriesModel
.setDefault( null );
257 this._saveSavedQueries();
261 * Rename a saved query
263 * @param {string} queryID Query id
264 * @param {string} newLabel New label for the query
266 mw
.rcfilters
.Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
267 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
270 queryItem
.updateLabel( newLabel
);
272 this._saveSavedQueries();
276 * Set a saved query as default
278 * @param {string} queryID Query Id. If null is given, default
281 mw
.rcfilters
.Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
282 this.savedQueriesModel
.setDefault( queryID
);
283 this._saveSavedQueries();
289 * @param {string} queryID Query id
291 mw
.rcfilters
.Controller
.prototype.applySavedQuery = function ( queryID
) {
292 var data
, highlights
,
293 queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
296 data
= queryItem
.getData();
297 highlights
= data
.highlights
;
299 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
300 highlights
.highlight
= highlights
.highlights
|| highlights
.highlight
;
302 // Update model state from filters
303 this.filtersModel
.toggleFiltersSelected( data
.filters
);
305 // Update highlight state
306 this.filtersModel
.toggleHighlight( !!Number( highlights
.highlight
) );
307 this.filtersModel
.getItems().forEach( function ( filterItem
) {
308 var color
= highlights
[ filterItem
.getName() ];
310 filterItem
.setHighlightColor( color
);
312 filterItem
.clearHighlightColor();
316 // Check all filter interactions
317 this.filtersModel
.reassessFilterInteractions();
319 this.updateChangesList();
324 * Check whether the current filter and highlight state exists
325 * in the saved queries model.
327 * @return {boolean} Query exists
329 mw
.rcfilters
.Controller
.prototype.findQueryMatchingCurrentState = function () {
330 var highlightedItems
= {};
332 // Prepare highlights of the current query
333 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
334 highlightedItems
[ item
.getName() ] = item
.getHighlightColor();
336 highlightedItems
.highlight
= this.filtersModel
.isHighlightEnabled();
338 return this.savedQueriesModel
.findMatchingQuery(
340 filters
: this.filtersModel
.getSelectedState(),
341 highlights
: highlightedItems
347 * Get an object representing the base state of parameters
350 * This is meant to make sure that the saved queries that are
351 * in memory are always the same structure as what we would get
352 * by calling the current model's "getSelectedState" and by checking
355 * In cases where a user saved a query when the system had a certain
356 * set of filters, and then a filter was added to the system, we want
357 * to make sure that the stored queries can still be comparable to
358 * the current state, which means that we need the base state for
361 * - Saved queries are stored in "minimal" view (only changed filters
362 * are stored); When we initialize the system, we merge each minimal
363 * query with the base state (using 'getNormalizedFilters') so all
364 * saved queries have the exact same structure as what we would get
365 * by checking the getSelectedState of the filter.
366 * - When we save the queries, we minimize the object to only represent
367 * whatever has actually changed, rather than store the entire
368 * object. To check what actually is different so we can store it,
369 * we need to obtain a base state to compare against, this is
370 * what #_getMinimalFilterList does
372 mw
.rcfilters
.Controller
.prototype._buildBaseFilterState = function () {
373 var defaultParams
= this.filtersModel
.getDefaultParams(),
374 highlightedItems
= {};
376 // Prepare highlights
377 this.filtersModel
.getItemsSupportingHighlights().forEach( function ( item
) {
378 highlightedItems
[ item
.getName() ] = null;
380 highlightedItems
.highlight
= false;
382 this.baseFilterState
= {
383 filters
: this.filtersModel
.getFiltersFromParameters( defaultParams
),
384 highlights
: highlightedItems
389 * Build an empty representation of the parameters, where all parameters
390 * are either set to '0' or '' depending on their type.
391 * This must run during initialization, before highlights are set.
393 mw
.rcfilters
.Controller
.prototype._buildEmptyParameterState = function () {
394 var emptyParams
= this.filtersModel
.getParametersFromFilters( {} ),
395 emptyHighlights
= this.filtersModel
.getHighlightParameters();
397 this.emptyParameterState
= $.extend(
407 * Get an object representing the base filter state of both
408 * filters and highlights. The structure is similar to what we use
409 * to store each query in the saved queries object:
415 * filterName: (string|null)
419 * @return {Object} Object representing the base state of
420 * parameters and highlights
422 mw
.rcfilters
.Controller
.prototype._getBaseFilterState = function () {
423 return this.baseFilterState
;
427 * Get an object representing the base state of parameters
428 * and highlights. The structure is similar to what we use
429 * to store each query in the saved queries object:
432 * param2: "value1|value2"
435 * @return {Object} Object representing the base state of
436 * parameters and highlights
438 mw
.rcfilters
.Controller
.prototype._getEmptyParameterState = function () {
439 return this.emptyParameterState
;
443 * Get an object that holds only the parameters and highlights that have
444 * values different than the base default value.
446 * This is the reverse of the normalization we do initially on loading and
447 * initializing the saved queries model.
449 * @param {Object} valuesObject Object representing the state of both
450 * filters and highlights in its normalized version, to be minimized.
451 * @return {Object} Minimal filters and highlights list
453 mw
.rcfilters
.Controller
.prototype._getMinimalFilterList = function ( valuesObject
) {
454 var result
= { filters
: {}, highlights
: {} },
455 baseState
= this._getBaseFilterState();
458 $.each( valuesObject
.filters
, function ( name
, value
) {
459 if ( baseState
.filters
!== undefined && baseState
.filters
[ name
] !== value
) {
460 result
.filters
[ name
] = value
;
464 $.each( valuesObject
.highlights
, function ( name
, value
) {
465 if ( baseState
.highlights
!== undefined && baseState
.highlights
[ name
] !== value
) {
466 result
.highlights
[ name
] = value
;
474 * Save the current state of the saved queries model with all
475 * query item representation in the user settings.
477 mw
.rcfilters
.Controller
.prototype._saveSavedQueries = function () {
479 state
= this.savedQueriesModel
.getState(),
482 // Minimize before save
483 $.each( state
.queries
, function ( queryID
, info
) {
484 state
.queries
[ queryID
].data
= controller
._getMinimalFilterList( info
.data
);
488 stringified
= JSON
.stringify( state
);
490 if ( stringified
.length
> 65535 ) {
491 // Sanity check, since the preference can only hold that.
495 // Save the preference
496 new mw
.Api().saveOption( 'rcfilters-saved-queries', stringified
);
497 // Update the preference for this session
498 mw
.user
.options
.set( 'rcfilters-saved-queries', stringified
);
502 * Synchronize the URL with the current state of the filters
503 * without adding an history entry.
505 mw
.rcfilters
.Controller
.prototype.replaceUrl = function () {
506 window
.history
.replaceState(
507 { tag
: 'rcfilters' },
509 this._getUpdatedUri().toString()
514 * Update filter state (selection and highlighting) based
515 * on current URL values.
517 mw
.rcfilters
.Controller
.prototype.updateStateBasedOnUrl = function () {
518 var uri
= new mw
.Uri();
520 this._updateModelState( uri
.query
);
521 this.updateChangesList();
525 * Update the list of changes and notify the model
527 * @param {Object} [params] Extra parameters to add to the API call
529 mw
.rcfilters
.Controller
.prototype.updateChangesList = function ( params
) {
530 this._updateURL( params
);
531 this.changesListModel
.invalidate();
532 this._fetchChangesList()
535 function ( pieces
) {
536 var $changesListContent
= pieces
.changes
,
537 $fieldset
= pieces
.fieldset
;
538 this.changesListModel
.update( $changesListContent
, $fieldset
);
540 // Do nothing for failure
545 * Update the model state from given the given parameters.
547 * This is an internal method, and should only be used from inside
550 * @param {Object} parameters Object representing the parameters for
551 * filters and highlights
553 mw
.rcfilters
.Controller
.prototype._updateModelState = function ( parameters
) {
554 // Update filter states
555 this.filtersModel
.toggleFiltersSelected(
556 this.filtersModel
.getFiltersFromParameters(
561 // Update highlight state
562 this.filtersModel
.toggleHighlight( !!Number( parameters
.highlight
) );
563 this.filtersModel
.getItems().forEach( function ( filterItem
) {
564 var color
= parameters
[ filterItem
.getName() + '_color' ];
566 filterItem
.setHighlightColor( color
);
568 filterItem
.clearHighlightColor();
572 // Check all filter interactions
573 this.filtersModel
.reassessFilterInteractions();
577 * Get an object representing the default parameter state, whether
578 * it is from the model defaults or from the saved queries.
580 * @return {Object} Default parameters
582 mw
.rcfilters
.Controller
.prototype._getDefaultParams = function () {
583 var data
, queryHighlights
,
585 savedHighlights
= {},
586 defaultSavedQueryItem
= this.savedQueriesModel
.getItemByID( this.savedQueriesModel
.getDefault() );
588 if ( mw
.config
.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
589 defaultSavedQueryItem
) {
591 data
= defaultSavedQueryItem
.getData();
593 queryHighlights
= data
.highlights
|| {};
594 savedParams
= this.filtersModel
.getParametersFromFilters( data
.filters
|| {} );
596 // Translate highlights to parameters
597 savedHighlights
.highlight
= String( Number( queryHighlights
.highlight
) );
598 $.each( queryHighlights
, function ( filterName
, color
) {
599 if ( filterName
!== 'highlights' ) {
600 savedHighlights
[ filterName
+ '_color' ] = color
;
604 return $.extend( true, {}, savedParams
, savedHighlights
);
607 return this.filtersModel
.getDefaultParams();
611 * Update the URL of the page to reflect current filters
613 * This should not be called directly from outside the controller.
614 * If an action requires changing the URL, it should either use the
615 * highlighting actions below, or call #updateChangesList which does
616 * the uri corrections already.
618 * @param {Object} [params] Extra parameters to add to the API call
620 mw
.rcfilters
.Controller
.prototype._updateURL = function ( params
) {
621 var currentFilterState
, updatedFilterState
, updatedUri
,
623 notEquivalent = function ( obj1
, obj2
) {
624 var keys
= Object
.keys( obj1
).concat( Object
.keys( obj2
) );
625 return keys
.some( function ( key
) {
626 return obj1
[ key
] != obj2
[ key
]; // eslint-disable-line eqeqeq
630 params
= params
|| {};
632 updatedUri
= this._getUpdatedUri();
633 updatedUri
.extend( params
);
635 // Compare states instead of parameters
636 // This will allow us to always have a proper check of whether
637 // the requested new url is one to change or not, regardless of
638 // actual parameter visibility/representation in the URL
639 currentFilterState
= this.filtersModel
.getFiltersFromParameters( uri
.query
);
640 updatedFilterState
= this.filtersModel
.getFiltersFromParameters( updatedUri
.query
);
642 // Include highlight states
645 this.filtersModel
.extractHighlightValues( uri
.query
),
646 { highlight
: !!Number( uri
.query
.highlight
) }
650 this.filtersModel
.extractHighlightValues( updatedUri
.query
),
651 { highlight
: !!Number( updatedUri
.query
.highlight
) }
654 if ( notEquivalent( currentFilterState
, updatedFilterState
) ) {
655 if ( this.initializing
) {
656 // Initially, when we just build the first page load
657 // out of defaults, we want to replace the history
658 window
.history
.replaceState( { tag
: 'rcfilters' }, document
.title
, updatedUri
.toString() );
660 window
.history
.pushState( { tag
: 'rcfilters' }, document
.title
, updatedUri
.toString() );
666 * Get an updated mw.Uri object based on the model state
668 * @return {mw.Uri} Updated Uri
670 mw
.rcfilters
.Controller
.prototype._getUpdatedUri = function () {
671 var uri
= new mw
.Uri(),
672 highlightParams
= this.filtersModel
.getHighlightParameters(),
673 modelParameters
= this.filtersModel
.getParametersFromFilters(),
674 baseParams
= this._getEmptyParameterState();
676 // Minimize values of the model parameters; show only the values that
677 // are non-zero. We assume that all parameters that are not literally
678 // showing in the URL are set to zero or empty
679 $.each( modelParameters
, function ( paramName
, value
) {
680 if ( baseParams
[ paramName
] !== value
) {
681 uri
.query
[ paramName
] = value
;
683 // We need to remove this value from the url
684 delete uri
.query
[ paramName
];
689 if ( this.filtersModel
.isHighlightEnabled() ) {
690 uri
.query
.highlight
= Number( this.filtersModel
.isHighlightEnabled() );
692 delete uri
.query
.highlight
;
694 $.each( highlightParams
, function ( paramName
, value
) {
695 // Only output if it is different than the base parameters
696 if ( baseParams
[ paramName
] !== value
) {
697 uri
.query
[ paramName
] = value
;
699 delete uri
.query
[ paramName
];
707 * Fetch the list of changes from the server for the current filters
709 * @return {jQuery.Promise} Promise object that will resolve with the changes list
710 * or with a string denoting no results.
712 mw
.rcfilters
.Controller
.prototype._fetchChangesList = function () {
713 var uri
= this._getUpdatedUri(),
714 requestId
= ++this.requestCounter
,
715 latestRequest = function () {
716 return requestId
=== this.requestCounter
;
719 return $.ajax( uri
.toString(), { contentType
: 'html' } )
724 if ( !latestRequest() ) {
725 return $.Deferred().reject();
728 $parsed
= $( $.parseHTML( html
) );
732 changes
: $parsed
.find( '.mw-changeslist' ).first().contents(),
734 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
738 function ( responseObj
) {
741 if ( !latestRequest() ) {
742 return $.Deferred().reject();
745 $parsed
= $( $.parseHTML( responseObj
.responseText
) );
747 // Force a resolve state to this promise
748 return $.Deferred().resolve( {
749 changes
: 'NO_RESULTS',
750 fieldset
: $parsed
.find( 'fieldset.rcoptions' ).first()
757 * Track usage of highlight feature
759 * @param {string} action
760 * @param {array|object|string} filters
762 mw
.rcfilters
.Controller
.prototype._trackHighlight = function ( action
, filters
) {
763 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
764 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
766 'event.ChangesListHighlights',
770 userId
: mw
.user
.getId()
775 }( mediaWiki
, jQuery
) );