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