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