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