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