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