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