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