Merge "RCFilters: Make namespace and tag features no longer experimental"
[lhc/web/wiklou.git] / resources / src / mediawiki.rcfilters / mw.rcfilters.Controller.js
1 ( function ( mw, $ ) {
2 /* eslint no-underscore-dangle: "off" */
3 /**
4 * Controller for the filters in Recent Changes
5 * @class
6 *
7 * @constructor
8 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
9 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
10 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
11 */
12 mw.rcfilters.Controller = function MwRcfiltersController( filtersModel, changesListModel, savedQueriesModel ) {
13 this.filtersModel = filtersModel;
14 this.changesListModel = changesListModel;
15 this.savedQueriesModel = savedQueriesModel;
16 this.requestCounter = 0;
17 this.baseFilterState = {};
18 this.uriProcessor = null;
19 this.initializing = false;
20
21 this.prevLoggedItems = [];
22 };
23
24 /* Initialization */
25 OO.initClass( mw.rcfilters.Controller );
26
27 /**
28 * Initialize the filter and parameter states
29 *
30 * @param {Array} filterStructure Filter definition and structure for the model
31 * @param {Object} [namespaceStructure] Namespace definition
32 * @param {Object} [tagList] Tag definition
33 */
34 mw.rcfilters.Controller.prototype.initialize = function ( filterStructure, namespaceStructure, tagList ) {
35 var parsedSavedQueries,
36 controller = this,
37 views = {},
38 items = [],
39 uri = new mw.Uri(),
40 $changesList = $( '.mw-changeslist' ).first().contents();
41
42 // Prepare views
43 if ( namespaceStructure ) {
44 items = [];
45 $.each( namespaceStructure, function ( namespaceID, label ) {
46 // Build and clean up the individual namespace items definition
47 items.push( {
48 name: namespaceID,
49 label: label || mw.msg( 'blanknamespace' ),
50 description: '',
51 identifiers: [
52 ( namespaceID < 0 || namespaceID % 2 === 0 ) ?
53 'subject' : 'talk'
54 ],
55 cssClass: 'mw-changeslist-ns-' + namespaceID
56 } );
57 } );
58
59 views.namespaces = {
60 title: mw.msg( 'namespaces' ),
61 trigger: ':',
62 groups: [ {
63 // Group definition (single group)
64 name: 'namespace', // parameter name is singular
65 type: 'string_options',
66 title: mw.msg( 'namespaces' ),
67 labelPrefixKey: { 'default': 'rcfilters-tag-prefix-namespace', inverted: 'rcfilters-tag-prefix-namespace-inverted' },
68 separator: ';',
69 fullCoverage: true,
70 filters: items
71 } ]
72 };
73 }
74 if ( tagList ) {
75 views.tags = {
76 title: mw.msg( 'rcfilters-view-tags' ),
77 trigger: '#',
78 groups: [ {
79 // Group definition (single group)
80 name: 'tagfilter', // Parameter name
81 type: 'string_options',
82 title: 'rcfilters-view-tags', // Message key
83 labelPrefixKey: 'rcfilters-tag-prefix-tags',
84 separator: '|',
85 fullCoverage: false,
86 filters: tagList
87 } ]
88 };
89 }
90
91 // Add parameter range operations
92 views.range = {
93 groups: [
94 {
95 name: 'limit',
96 type: 'single_option',
97 title: '', // Because it's a hidden group, this title actually appears nowhere
98 hidden: true,
99 allowArbitrary: true,
100 validate: $.isNumeric,
101 sortFunc: function ( a, b ) { return Number( a.name ) - Number( b.name ); },
102 'default': mw.user.options.get( 'rclimit' ),
103 filters: [ 50, 100, 250, 500 ].map( function ( num ) {
104 return controller._createFilterDataFromNumber( num, num );
105 } )
106 },
107 {
108 name: 'days',
109 type: 'single_option',
110 title: '', // Because it's a hidden group, this title actually appears nowhere
111 hidden: true,
112 allowArbitrary: true,
113 validate: $.isNumeric,
114 sortFunc: function ( a, b ) { return Number( a.name ) - Number( b.name ); },
115 numToLabelFunc: function ( i ) {
116 return Number( i ) < 1 ?
117 ( Number( i ) * 24 ).toFixed( 2 ) :
118 Number( i );
119 },
120 'default': mw.user.options.get( 'rcdays' ),
121 filters: [
122 // Hours (1, 2, 6, 12)
123 0.04166, 0.0833, 0.25, 0.5,
124 // Days
125 1, 3, 7, 14, 30
126 ].map( function ( num ) {
127 return controller._createFilterDataFromNumber(
128 num,
129 // Convert fractions of days to number of hours for the labels
130 num < 1 ? Math.round( num * 24 ) : num
131 );
132 } )
133 }
134 ]
135 };
136
137 // Before we do anything, we need to see if we require additional items in the
138 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
139 // groups; if we ever expand it, this might need further generalization:
140 $.each( views, function ( viewName, viewData ) {
141 viewData.groups.forEach( function ( groupData ) {
142 var extraValues = [];
143 if ( groupData.allowArbitrary ) {
144 // If the value in the URI isn't in the group, add it
145 if ( uri.query[ groupData.name ] !== undefined ) {
146 extraValues.push( uri.query[ groupData.name ] );
147 }
148 // If the default value isn't in the group, add it
149 if ( groupData.default !== undefined ) {
150 extraValues.push( String( groupData.default ) );
151 }
152 controller.addNumberValuesToGroup( groupData, extraValues );
153 }
154 } );
155 } );
156
157 // Initialize the model
158 this.filtersModel.initializeFilters( filterStructure, views );
159
160 this._buildBaseFilterState();
161
162 this.uriProcessor = new mw.rcfilters.UriProcessor(
163 this.filtersModel
164 );
165
166 try {
167 parsedSavedQueries = JSON.parse( mw.user.options.get( 'rcfilters-saved-queries' ) || '{}' );
168 } catch ( err ) {
169 parsedSavedQueries = {};
170 }
171
172 // The queries are saved in a minimized state, so we need
173 // to send over the base state so the saved queries model
174 // can normalize them per each query item
175 this.savedQueriesModel.initialize(
176 parsedSavedQueries,
177 this._getBaseFilterState()
178 );
179
180 // Check whether we need to load defaults.
181 // We do this by checking whether the current URI query
182 // contains any parameters recognized by the system.
183 // If it does, we load the given state.
184 // If it doesn't, we have no values at all, and we assume
185 // the user loads the base-page and we load defaults.
186 // Defaults should only be applied on load (if necessary)
187 // or on request
188 this.initializing = true;
189 if (
190 this.savedQueriesModel.getDefault() &&
191 !this.uriProcessor.doesQueryContainRecognizedParams( uri.query )
192 ) {
193 // We have defaults from a saved query.
194 // We will load them straight-forward (as if
195 // they were clicked in the menu) so we trigger
196 // a full ajax request and change of URL
197 this.applySavedQuery( this.savedQueriesModel.getDefault() );
198 } else {
199 // There are either recognized parameters in the URL
200 // or there are none, but there is also no default
201 // saved query (so defaults are from the backend)
202 // We want to update the state but not fetch results
203 // again
204 this.updateStateFromUrl( false );
205
206 // Update the changes list with the existing data
207 // so it gets processed
208 this.changesListModel.update(
209 $changesList.length ? $changesList : 'NO_RESULTS',
210 $( 'fieldset.rcoptions' ).first(),
211 true // We're using existing DOM elements
212 );
213 }
214
215 this.initializing = false;
216 this.switchView( 'default' );
217 };
218
219 /**
220 * Create filter data from a number, for the filters that are numerical value
221 *
222 * @param {Number} num Number
223 * @param {Number} numForDisplay Number for the label
224 * @return {Object} Filter data
225 */
226 mw.rcfilters.Controller.prototype._createFilterDataFromNumber = function ( num, numForDisplay ) {
227 return {
228 name: String( num ),
229 label: mw.language.convertNumber( numForDisplay )
230 };
231 };
232
233 /**
234 * Add an arbitrary values to groups that allow arbitrary values
235 *
236 * @param {Object} groupData Group data
237 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
238 */
239 mw.rcfilters.Controller.prototype.addNumberValuesToGroup = function ( groupData, arbitraryValues ) {
240 var controller = this;
241
242 arbitraryValues = Array.isArray( arbitraryValues ) ? arbitraryValues : [ arbitraryValues ];
243
244 // This is only true for single_option group
245 // We assume these are the only groups that will allow for
246 // arbitrary, since it doesn't make any sense for the other
247 // groups.
248 arbitraryValues.forEach( function ( val ) {
249 if (
250 // If the group allows for arbitrary data
251 groupData.allowArbitrary &&
252 // and it is single_option (or string_options, but we
253 // don't have cases of those yet, nor do we plan to)
254 groupData.type === 'single_option' &&
255 // and, if there is a validate method and it passes on
256 // the data
257 ( !groupData.validate || groupData.validate( val ) ) &&
258 // but if that value isn't already in the definition
259 groupData.filters
260 .map( function ( filterData ) {
261 return filterData.name;
262 } )
263 .indexOf( val ) === -1
264 ) {
265 // Add the filter information
266 groupData.filters.push( controller._createFilterDataFromNumber(
267 val,
268 groupData.numToLabelFunc ?
269 groupData.numToLabelFunc( val ) :
270 val
271 ) );
272
273 // If there's a sort function set up, re-sort the values
274 if ( groupData.sortFunc ) {
275 groupData.filters.sort( groupData.sortFunc );
276 }
277 }
278 } );
279 };
280
281 /**
282 * Switch the view of the filters model
283 *
284 * @param {string} view Requested view
285 */
286 mw.rcfilters.Controller.prototype.switchView = function ( view ) {
287 this.filtersModel.switchView( view );
288 };
289
290 /**
291 * Reset to default filters
292 */
293 mw.rcfilters.Controller.prototype.resetToDefaults = function () {
294 this.uriProcessor.updateModelBasedOnQuery( this._getDefaultParams() );
295 this.updateChangesList();
296 };
297
298 /**
299 * Empty all selected filters
300 */
301 mw.rcfilters.Controller.prototype.emptyFilters = function () {
302 var highlightedFilterNames = this.filtersModel
303 .getHighlightedItems()
304 .map( function ( filterItem ) { return { name: filterItem.getName() }; } );
305
306 this.filtersModel.emptyAllFilters();
307 this.filtersModel.clearAllHighlightColors();
308 // Check all filter interactions
309 this.filtersModel.reassessFilterInteractions();
310
311 this.updateChangesList();
312
313 if ( highlightedFilterNames ) {
314 this._trackHighlight( 'clearAll', highlightedFilterNames );
315 }
316 };
317
318 /**
319 * Update the selected state of a filter
320 *
321 * @param {string} filterName Filter name
322 * @param {boolean} [isSelected] Filter selected state
323 */
324 mw.rcfilters.Controller.prototype.toggleFilterSelect = function ( filterName, isSelected ) {
325 var filterItem = this.filtersModel.getItemByName( filterName );
326
327 if ( !filterItem ) {
328 // If no filter was found, break
329 return;
330 }
331
332 isSelected = isSelected === undefined ? !filterItem.isSelected() : isSelected;
333
334 if ( filterItem.isSelected() !== isSelected ) {
335 this.filtersModel.toggleFilterSelected( filterName, isSelected );
336
337 this.updateChangesList();
338
339 // Check filter interactions
340 this.filtersModel.reassessFilterInteractions( filterItem );
341 }
342 };
343
344 /**
345 * Clear both highlight and selection of a filter
346 *
347 * @param {string} filterName Name of the filter item
348 */
349 mw.rcfilters.Controller.prototype.clearFilter = function ( filterName ) {
350 var filterItem = this.filtersModel.getItemByName( filterName ),
351 isHighlighted = filterItem.isHighlighted();
352
353 if ( filterItem.isSelected() || isHighlighted ) {
354 this.filtersModel.clearHighlightColor( filterName );
355 this.filtersModel.toggleFilterSelected( filterName, false );
356 this.updateChangesList();
357 this.filtersModel.reassessFilterInteractions( filterItem );
358
359 // Log filter grouping
360 this.trackFilterGroupings( 'removefilter' );
361 }
362
363 if ( isHighlighted ) {
364 this._trackHighlight( 'clear', filterName );
365 }
366 };
367
368 /**
369 * Toggle the highlight feature on and off
370 */
371 mw.rcfilters.Controller.prototype.toggleHighlight = function () {
372 this.filtersModel.toggleHighlight();
373 this._updateURL();
374
375 if ( this.filtersModel.isHighlightEnabled() ) {
376 mw.hook( 'RcFilters.highlight.enable' ).fire();
377 }
378 };
379
380 /**
381 * Toggle the namespaces inverted feature on and off
382 */
383 mw.rcfilters.Controller.prototype.toggleInvertedNamespaces = function () {
384 this.filtersModel.toggleInvertedNamespaces();
385 this.updateChangesList();
386 };
387
388 /**
389 * Set the highlight color for a filter item
390 *
391 * @param {string} filterName Name of the filter item
392 * @param {string} color Selected color
393 */
394 mw.rcfilters.Controller.prototype.setHighlightColor = function ( filterName, color ) {
395 this.filtersModel.setHighlightColor( filterName, color );
396 this._updateURL();
397 this._trackHighlight( 'set', { name: filterName, color: color } );
398 };
399
400 /**
401 * Clear highlight for a filter item
402 *
403 * @param {string} filterName Name of the filter item
404 */
405 mw.rcfilters.Controller.prototype.clearHighlightColor = function ( filterName ) {
406 this.filtersModel.clearHighlightColor( filterName );
407 this._updateURL();
408 this._trackHighlight( 'clear', filterName );
409 };
410
411 /**
412 * Enable or disable live updates.
413 * @param {boolean} enable True to enable, false to disable
414 */
415 mw.rcfilters.Controller.prototype.toggleLiveUpdate = function ( enable ) {
416 if ( enable && !this.liveUpdateTimeout ) {
417 this._scheduleLiveUpdate();
418 } else if ( !enable && this.liveUpdateTimeout ) {
419 clearTimeout( this.liveUpdateTimeout );
420 this.liveUpdateTimeout = null;
421 }
422 };
423
424 /**
425 * Set a timeout for the next live update.
426 * @private
427 */
428 mw.rcfilters.Controller.prototype._scheduleLiveUpdate = function () {
429 this.liveUpdateTimeout = setTimeout( this._doLiveUpdate.bind( this ), 3000 );
430 };
431
432 /**
433 * Perform a live update.
434 * @private
435 */
436 mw.rcfilters.Controller.prototype._doLiveUpdate = function () {
437 var controller = this;
438 this.updateChangesList( {}, true )
439 .always( function () {
440 if ( controller.liveUpdateTimeout ) {
441 // Live update was not disabled in the meantime
442 controller._scheduleLiveUpdate();
443 }
444 } );
445 };
446
447 /**
448 * Save the current model state as a saved query
449 *
450 * @param {string} [label] Label of the saved query
451 */
452 mw.rcfilters.Controller.prototype.saveCurrentQuery = function ( label ) {
453 var highlightedItems = {},
454 highlightEnabled = this.filtersModel.isHighlightEnabled();
455
456 // Prepare highlights
457 this.filtersModel.getHighlightedItems().forEach( function ( item ) {
458 highlightedItems[ item.getName() ] = highlightEnabled ?
459 item.getHighlightColor() : null;
460 } );
461 // These are filter states; highlight is stored as boolean
462 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
463
464 // Add item
465 this.savedQueriesModel.addNewQuery(
466 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
467 {
468 filters: this.filtersModel.getSelectedState(),
469 highlights: highlightedItems,
470 invert: this.filtersModel.areNamespacesInverted()
471 }
472 );
473
474 // Save item
475 this._saveSavedQueries();
476 };
477
478 /**
479 * Remove a saved query
480 *
481 * @param {string} queryID Query id
482 */
483 mw.rcfilters.Controller.prototype.removeSavedQuery = function ( queryID ) {
484 this.savedQueriesModel.removeQuery( queryID );
485
486 this._saveSavedQueries();
487 };
488
489 /**
490 * Rename a saved query
491 *
492 * @param {string} queryID Query id
493 * @param {string} newLabel New label for the query
494 */
495 mw.rcfilters.Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
496 var queryItem = this.savedQueriesModel.getItemByID( queryID );
497
498 if ( queryItem ) {
499 queryItem.updateLabel( newLabel );
500 }
501 this._saveSavedQueries();
502 };
503
504 /**
505 * Set a saved query as default
506 *
507 * @param {string} queryID Query Id. If null is given, default
508 * query is reset.
509 */
510 mw.rcfilters.Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
511 this.savedQueriesModel.setDefault( queryID );
512 this._saveSavedQueries();
513 };
514
515 /**
516 * Load a saved query
517 *
518 * @param {string} queryID Query id
519 */
520 mw.rcfilters.Controller.prototype.applySavedQuery = function ( queryID ) {
521 var data, highlights,
522 queryItem = this.savedQueriesModel.getItemByID( queryID );
523
524 if ( queryItem ) {
525 data = queryItem.getData();
526 highlights = data.highlights;
527
528 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
529 highlights.highlight = highlights.highlights || highlights.highlight;
530
531 // Update model state from filters
532 this.filtersModel.toggleFiltersSelected( data.filters );
533
534 // Update namespace inverted property
535 this.filtersModel.toggleInvertedNamespaces( !!Number( data.invert ) );
536
537 // Update highlight state
538 this.filtersModel.toggleHighlight( !!Number( highlights.highlight ) );
539 this.filtersModel.getItems().forEach( function ( filterItem ) {
540 var color = highlights[ filterItem.getName() ];
541 if ( color ) {
542 filterItem.setHighlightColor( color );
543 } else {
544 filterItem.clearHighlightColor();
545 }
546 } );
547
548 // Check all filter interactions
549 this.filtersModel.reassessFilterInteractions();
550
551 this.updateChangesList();
552
553 // Log filter grouping
554 this.trackFilterGroupings( 'savedfilters' );
555 }
556 };
557
558 /**
559 * Check whether the current filter and highlight state exists
560 * in the saved queries model.
561 *
562 * @return {boolean} Query exists
563 */
564 mw.rcfilters.Controller.prototype.findQueryMatchingCurrentState = function () {
565 var highlightedItems = {};
566
567 // Prepare highlights of the current query
568 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
569 highlightedItems[ item.getName() ] = item.getHighlightColor();
570 } );
571 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
572
573 return this.savedQueriesModel.findMatchingQuery(
574 {
575 filters: this.filtersModel.getSelectedState(),
576 highlights: highlightedItems,
577 invert: this.filtersModel.areNamespacesInverted()
578 }
579 );
580 };
581
582 /**
583 * Get an object representing the base state of parameters
584 * and highlights.
585 *
586 * This is meant to make sure that the saved queries that are
587 * in memory are always the same structure as what we would get
588 * by calling the current model's "getSelectedState" and by checking
589 * highlight items.
590 *
591 * In cases where a user saved a query when the system had a certain
592 * set of filters, and then a filter was added to the system, we want
593 * to make sure that the stored queries can still be comparable to
594 * the current state, which means that we need the base state for
595 * two operations:
596 *
597 * - Saved queries are stored in "minimal" view (only changed filters
598 * are stored); When we initialize the system, we merge each minimal
599 * query with the base state (using 'getNormalizedFilters') so all
600 * saved queries have the exact same structure as what we would get
601 * by checking the getSelectedState of the filter.
602 * - When we save the queries, we minimize the object to only represent
603 * whatever has actually changed, rather than store the entire
604 * object. To check what actually is different so we can store it,
605 * we need to obtain a base state to compare against, this is
606 * what #_getMinimalFilterList does
607 */
608 mw.rcfilters.Controller.prototype._buildBaseFilterState = function () {
609 var defaultParams = this.filtersModel.getDefaultParams(),
610 highlightedItems = {};
611
612 // Prepare highlights
613 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
614 highlightedItems[ item.getName() ] = null;
615 } );
616 highlightedItems.highlight = false;
617
618 this.baseFilterState = {
619 filters: this.filtersModel.getFiltersFromParameters( defaultParams ),
620 highlights: highlightedItems,
621 invert: false
622 };
623 };
624
625 /**
626 * Get an object representing the base filter state of both
627 * filters and highlights. The structure is similar to what we use
628 * to store each query in the saved queries object:
629 * {
630 * filters: {
631 * filterName: (bool)
632 * },
633 * highlights: {
634 * filterName: (string|null)
635 * }
636 * }
637 *
638 * @return {Object} Object representing the base state of
639 * parameters and highlights
640 */
641 mw.rcfilters.Controller.prototype._getBaseFilterState = function () {
642 return this.baseFilterState;
643 };
644
645 /**
646 * Get an object that holds only the parameters and highlights that have
647 * values different than the base default value.
648 *
649 * This is the reverse of the normalization we do initially on loading and
650 * initializing the saved queries model.
651 *
652 * @param {Object} valuesObject Object representing the state of both
653 * filters and highlights in its normalized version, to be minimized.
654 * @return {Object} Minimal filters and highlights list
655 */
656 mw.rcfilters.Controller.prototype._getMinimalFilterList = function ( valuesObject ) {
657 var result = { filters: {}, highlights: {} },
658 baseState = this._getBaseFilterState();
659
660 // XOR results
661 $.each( valuesObject.filters, function ( name, value ) {
662 if ( baseState.filters !== undefined && baseState.filters[ name ] !== value ) {
663 result.filters[ name ] = value;
664 }
665 } );
666
667 $.each( valuesObject.highlights, function ( name, value ) {
668 if ( baseState.highlights !== undefined && baseState.highlights[ name ] !== value ) {
669 result.highlights[ name ] = value;
670 }
671 } );
672
673 return result;
674 };
675
676 /**
677 * Save the current state of the saved queries model with all
678 * query item representation in the user settings.
679 */
680 mw.rcfilters.Controller.prototype._saveSavedQueries = function () {
681 var stringified,
682 state = this.savedQueriesModel.getState(),
683 controller = this;
684
685 // Minimize before save
686 $.each( state.queries, function ( queryID, info ) {
687 state.queries[ queryID ].data = controller._getMinimalFilterList( info.data );
688 } );
689
690 // Stringify state
691 stringified = JSON.stringify( state );
692
693 if ( stringified.length > 65535 ) {
694 // Sanity check, since the preference can only hold that.
695 return;
696 }
697
698 // Save the preference
699 new mw.Api().saveOption( 'rcfilters-saved-queries', stringified );
700 // Update the preference for this session
701 mw.user.options.set( 'rcfilters-saved-queries', stringified );
702 };
703
704 /**
705 * Synchronize the URL with the current state of the filters
706 * without adding an history entry.
707 */
708 mw.rcfilters.Controller.prototype.replaceUrl = function () {
709 mw.rcfilters.UriProcessor.static.replaceState( this._getUpdatedUri() );
710 };
711
712 /**
713 * Update filter state (selection and highlighting) based
714 * on current URL values.
715 *
716 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
717 * list based on the updated model.
718 */
719 mw.rcfilters.Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
720 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
721
722 this.uriProcessor.updateModelBasedOnQuery( new mw.Uri().query );
723
724 // Only update and fetch new results if it is requested
725 if ( fetchChangesList ) {
726 this.updateChangesList();
727 }
728 };
729
730 /**
731 * Update the list of changes and notify the model
732 *
733 * @param {Object} [params] Extra parameters to add to the API call
734 * @param {boolean} [isLiveUpdate] Don't update the URL or invalidate the changes list
735 * @return {jQuery.Promise} Promise that is resolved when the update is complete
736 */
737 mw.rcfilters.Controller.prototype.updateChangesList = function ( params, isLiveUpdate ) {
738 if ( !isLiveUpdate ) {
739 this._updateURL( params );
740 this.changesListModel.invalidate();
741 }
742 return this._fetchChangesList()
743 .then(
744 // Success
745 function ( pieces ) {
746 var $changesListContent = pieces.changes,
747 $fieldset = pieces.fieldset;
748 this.changesListModel.update( $changesListContent, $fieldset );
749 }.bind( this )
750 // Do nothing for failure
751 );
752 };
753
754 /**
755 * Get an object representing the default parameter state, whether
756 * it is from the model defaults or from the saved queries.
757 *
758 * @return {Object} Default parameters
759 */
760 mw.rcfilters.Controller.prototype._getDefaultParams = function () {
761 var data, queryHighlights,
762 savedParams = {},
763 savedHighlights = {},
764 defaultSavedQueryItem = this.savedQueriesModel.getItemByID( this.savedQueriesModel.getDefault() );
765
766 if ( mw.config.get( 'wgStructuredChangeFiltersEnableSaving' ) &&
767 defaultSavedQueryItem ) {
768
769 data = defaultSavedQueryItem.getData();
770
771 queryHighlights = data.highlights || {};
772 savedParams = this.filtersModel.getParametersFromFilters( data.filters || {} );
773
774 // Translate highlights to parameters
775 savedHighlights.highlight = String( Number( queryHighlights.highlight ) );
776 $.each( queryHighlights, function ( filterName, color ) {
777 if ( filterName !== 'highlights' ) {
778 savedHighlights[ filterName + '_color' ] = color;
779 }
780 } );
781
782 return $.extend( true, {}, savedParams, savedHighlights );
783 }
784
785 return this.filtersModel.getDefaultParams();
786 };
787
788 /**
789 * Update the URL of the page to reflect current filters
790 *
791 * This should not be called directly from outside the controller.
792 * If an action requires changing the URL, it should either use the
793 * highlighting actions below, or call #updateChangesList which does
794 * the uri corrections already.
795 *
796 * @param {Object} [params] Extra parameters to add to the API call
797 */
798 mw.rcfilters.Controller.prototype._updateURL = function ( params ) {
799 var currentUri = new mw.Uri(),
800 updatedUri = this._getUpdatedUri();
801
802 updatedUri.extend( params || {} );
803
804 if (
805 this.uriProcessor.getVersion( currentUri.query ) !== 2 ||
806 this.uriProcessor.isNewState( currentUri.query, updatedUri.query )
807 ) {
808 mw.rcfilters.UriProcessor.static.replaceState( updatedUri );
809 }
810 };
811
812 /**
813 * Get an updated mw.Uri object based on the model state
814 *
815 * @return {mw.Uri} Updated Uri
816 */
817 mw.rcfilters.Controller.prototype._getUpdatedUri = function () {
818 var uri = new mw.Uri();
819
820 // Minimize url
821 uri.query = this.uriProcessor.minimizeQuery(
822 $.extend(
823 true,
824 {},
825 // We want to retain unrecognized params
826 // The uri params from model will override
827 // any recognized value in the current uri
828 // query, retain unrecognized params, and
829 // the result will then be minimized
830 uri.query,
831 this.uriProcessor.getUriParametersFromModel(),
832 { urlversion: '2' }
833 )
834 );
835
836 return uri;
837 };
838
839 /**
840 * Fetch the list of changes from the server for the current filters
841 *
842 * @return {jQuery.Promise} Promise object that will resolve with the changes list
843 * or with a string denoting no results.
844 */
845 mw.rcfilters.Controller.prototype._fetchChangesList = function () {
846 var uri = this._getUpdatedUri(),
847 requestId = ++this.requestCounter,
848 latestRequest = function () {
849 return requestId === this.requestCounter;
850 }.bind( this );
851
852 return $.ajax( uri.toString(), { contentType: 'html' } )
853 .then(
854 // Success
855 function ( html ) {
856 var $parsed;
857 if ( !latestRequest() ) {
858 return $.Deferred().reject();
859 }
860
861 $parsed = $( $.parseHTML( html ) );
862
863 return {
864 // Changes list
865 changes: $parsed.find( '.mw-changeslist' ).first().contents(),
866 // Fieldset
867 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
868 };
869 },
870 // Failure
871 function ( responseObj ) {
872 var $parsed;
873
874 if ( !latestRequest() ) {
875 return $.Deferred().reject();
876 }
877
878 $parsed = $( $.parseHTML( responseObj.responseText ) );
879
880 // Force a resolve state to this promise
881 return $.Deferred().resolve( {
882 changes: 'NO_RESULTS',
883 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
884 } ).promise();
885 }
886 );
887 };
888
889 /**
890 * Track usage of highlight feature
891 *
892 * @param {string} action
893 * @param {Array|Object|string} filters
894 */
895 mw.rcfilters.Controller.prototype._trackHighlight = function ( action, filters ) {
896 filters = typeof filters === 'string' ? { name: filters } : filters;
897 filters = !Array.isArray( filters ) ? [ filters ] : filters;
898 mw.track(
899 'event.ChangesListHighlights',
900 {
901 action: action,
902 filters: filters,
903 userId: mw.user.getId()
904 }
905 );
906 };
907
908 /**
909 * Track filter grouping usage
910 *
911 * @param {string} action Action taken
912 */
913 mw.rcfilters.Controller.prototype.trackFilterGroupings = function ( action ) {
914 var controller = this,
915 rightNow = new Date().getTime(),
916 randomIdentifier = String( mw.user.sessionId() ) + String( rightNow ) + String( Math.random() ),
917 // Get all current filters
918 filters = this.filtersModel.getSelectedItems().map( function ( item ) {
919 return item.getName();
920 } );
921
922 action = action || 'filtermenu';
923
924 // Check if these filters were the ones we just logged previously
925 // (Don't log the same grouping twice, in case the user opens/closes)
926 // the menu without action, or with the same result
927 if (
928 // Only log if the two arrays are different in size
929 filters.length !== this.prevLoggedItems.length ||
930 // Or if any filters are not the same as the cached filters
931 filters.some( function ( filterName ) {
932 return controller.prevLoggedItems.indexOf( filterName ) === -1;
933 } ) ||
934 // Or if any cached filters are not the same as given filters
935 this.prevLoggedItems.some( function ( filterName ) {
936 return filters.indexOf( filterName ) === -1;
937 } )
938 ) {
939 filters.forEach( function ( filterName ) {
940 mw.track(
941 'event.ChangesListFilterGrouping',
942 {
943 action: action,
944 groupIdentifier: randomIdentifier,
945 filter: filterName,
946 userId: mw.user.getId()
947 }
948 );
949 } );
950
951 // Cache the filter names
952 this.prevLoggedItems = filters;
953 }
954 };
955 }( mediaWiki, jQuery ) );