Merge "Fix not parsed message on Special:Import"
[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 = {};
17 this.baseFilterState = {};
18 this.uriProcessor = null;
19 this.initializing = false;
20
21 this.prevLoggedItems = [];
22
23 this.FILTER_CHANGE = 'filterChange';
24 this.SHOW_NEW_CHANGES = 'showNewChanges';
25 this.LIVE_UPDATE = 'liveUpdate';
26 };
27
28 /* Initialization */
29 OO.initClass( mw.rcfilters.Controller );
30
31 /**
32 * Initialize the filter and parameter states
33 *
34 * @param {Array} filterStructure Filter definition and structure for the model
35 * @param {Object} [namespaceStructure] Namespace definition
36 * @param {Object} [tagList] Tag definition
37 */
38 mw.rcfilters.Controller.prototype.initialize = function ( filterStructure, namespaceStructure, tagList ) {
39 var parsedSavedQueries, limitDefault,
40 displayConfig = mw.config.get( 'StructuredChangeFiltersDisplayConfig' ),
41 controller = this,
42 views = {},
43 items = [],
44 uri = new mw.Uri(),
45 $changesList = $( '.mw-changeslist' ).first().contents();
46
47 // Prepare views
48 if ( namespaceStructure ) {
49 items = [];
50 $.each( namespaceStructure, function ( namespaceID, label ) {
51 // Build and clean up the individual namespace items definition
52 items.push( {
53 name: namespaceID,
54 label: label || mw.msg( 'blanknamespace' ),
55 description: '',
56 identifiers: [
57 ( namespaceID < 0 || namespaceID % 2 === 0 ) ?
58 'subject' : 'talk'
59 ],
60 cssClass: 'mw-changeslist-ns-' + namespaceID
61 } );
62 } );
63
64 views.namespaces = {
65 title: mw.msg( 'namespaces' ),
66 trigger: ':',
67 groups: [ {
68 // Group definition (single group)
69 name: 'namespace', // parameter name is singular
70 type: 'string_options',
71 title: mw.msg( 'namespaces' ),
72 labelPrefixKey: { 'default': 'rcfilters-tag-prefix-namespace', inverted: 'rcfilters-tag-prefix-namespace-inverted' },
73 separator: ';',
74 fullCoverage: true,
75 filters: items
76 } ]
77 };
78 }
79 if ( tagList ) {
80 views.tags = {
81 title: mw.msg( 'rcfilters-view-tags' ),
82 trigger: '#',
83 groups: [ {
84 // Group definition (single group)
85 name: 'tagfilter', // Parameter name
86 type: 'string_options',
87 title: 'rcfilters-view-tags', // Message key
88 labelPrefixKey: 'rcfilters-tag-prefix-tags',
89 separator: '|',
90 fullCoverage: false,
91 filters: tagList
92 } ]
93 };
94 }
95
96 // Convert the default from the old preference
97 // since the limit preference actually affects more
98 // than just the RecentChanges page
99 limitDefault = Number( mw.user.options.get( 'rclimit', '50' ) );
100
101 // Add parameter range operations
102 views.range = {
103 groups: [
104 {
105 name: 'limit',
106 type: 'single_option',
107 title: '', // Because it's a hidden group, this title actually appears nowhere
108 hidden: true,
109 allowArbitrary: true,
110 validate: $.isNumeric,
111 range: {
112 min: 0, // The server normalizes negative numbers to 0 results
113 max: 1000
114 },
115 sortFunc: function ( a, b ) { return Number( a.name ) - Number( b.name ); },
116 'default': String( limitDefault ),
117 // Temporarily making this not sticky until we resolve the problem
118 // with the misleading preference. Note that if this is to be permanent
119 // we should remove all sticky behavior methods completely
120 // See T172156
121 // isSticky: true,
122 filters: displayConfig.limitArray.map( function ( num ) {
123 return controller._createFilterDataFromNumber( num, num );
124 } )
125 },
126 {
127 name: 'days',
128 type: 'single_option',
129 title: '', // Because it's a hidden group, this title actually appears nowhere
130 hidden: true,
131 allowArbitrary: true,
132 validate: $.isNumeric,
133 range: {
134 min: 0,
135 max: displayConfig.maxDays
136 },
137 sortFunc: function ( a, b ) { return Number( a.name ) - Number( b.name ); },
138 numToLabelFunc: function ( i ) {
139 return Number( i ) < 1 ?
140 ( Number( i ) * 24 ).toFixed( 2 ) :
141 Number( i );
142 },
143 'default': mw.user.options.get( 'rcdays', '30' ),
144 // Temporarily making this not sticky while limit is not sticky, see above
145 // isSticky: true,
146 filters: [
147 // Hours (1, 2, 6, 12)
148 0.04166, 0.0833, 0.25, 0.5
149 // Days
150 ].concat( displayConfig.daysArray )
151 .map( function ( num ) {
152 return controller._createFilterDataFromNumber(
153 num,
154 // Convert fractions of days to number of hours for the labels
155 num < 1 ? Math.round( num * 24 ) : num
156 );
157 } )
158 }
159 ]
160 };
161
162 views.display = {
163 groups: [
164 {
165 name: 'display',
166 type: 'boolean',
167 title: '', // Because it's a hidden group, this title actually appears nowhere
168 hidden: true,
169 isSticky: true,
170 filters: [
171 {
172 name: 'enhanced',
173 'default': String( mw.user.options.get( 'usenewrc', 0 ) )
174 }
175 ]
176 }
177 ]
178 };
179
180 // Before we do anything, we need to see if we require additional items in the
181 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
182 // groups; if we ever expand it, this might need further generalization:
183 $.each( views, function ( viewName, viewData ) {
184 viewData.groups.forEach( function ( groupData ) {
185 var extraValues = [];
186 if ( groupData.allowArbitrary ) {
187 // If the value in the URI isn't in the group, add it
188 if ( uri.query[ groupData.name ] !== undefined ) {
189 extraValues.push( uri.query[ groupData.name ] );
190 }
191 // If the default value isn't in the group, add it
192 if ( groupData.default !== undefined ) {
193 extraValues.push( String( groupData.default ) );
194 }
195 controller.addNumberValuesToGroup( groupData, extraValues );
196 }
197 } );
198 } );
199
200 // Initialize the model
201 this.filtersModel.initializeFilters( filterStructure, views );
202
203 this._buildBaseFilterState();
204
205 this.uriProcessor = new mw.rcfilters.UriProcessor(
206 this.filtersModel
207 );
208
209 try {
210 parsedSavedQueries = JSON.parse( mw.user.options.get( 'rcfilters-saved-queries' ) || '{}' );
211 } catch ( err ) {
212 parsedSavedQueries = {};
213 }
214
215 // The queries are saved in a minimized state, so we need
216 // to send over the base state so the saved queries model
217 // can normalize them per each query item
218 this.savedQueriesModel.initialize(
219 parsedSavedQueries,
220 this._getBaseFilterState(),
221 // This is for backwards compatibility - delete all sticky filter states
222 Object.keys( this.filtersModel.getStickyFiltersState() )
223 );
224
225 // Check whether we need to load defaults.
226 // We do this by checking whether the current URI query
227 // contains any parameters recognized by the system.
228 // If it does, we load the given state.
229 // If it doesn't, we have no values at all, and we assume
230 // the user loads the base-page and we load defaults.
231 // Defaults should only be applied on load (if necessary)
232 // or on request
233 this.initializing = true;
234 if (
235 this.savedQueriesModel.getDefault() &&
236 !this.uriProcessor.doesQueryContainRecognizedParams( uri.query )
237 ) {
238 // We have defaults from a saved query.
239 // We will load them straight-forward (as if
240 // they were clicked in the menu) so we trigger
241 // a full ajax request and change of URL
242 this.applySavedQuery( this.savedQueriesModel.getDefault() );
243 } else {
244 // There are either recognized parameters in the URL
245 // or there are none, but there is also no default
246 // saved query (so defaults are from the backend)
247 // We want to update the state but not fetch results
248 // again
249 this.updateStateFromUrl( false );
250
251 // Update the changes list with the existing data
252 // so it gets processed
253 this.changesListModel.update(
254 $changesList.length ? $changesList : 'NO_RESULTS',
255 $( 'fieldset.rcoptions' ).first(),
256 true // We're using existing DOM elements
257 );
258 }
259
260 this.initializing = false;
261 this.switchView( 'default' );
262
263 this._scheduleLiveUpdate();
264 };
265
266 /**
267 * Create filter data from a number, for the filters that are numerical value
268 *
269 * @param {Number} num Number
270 * @param {Number} numForDisplay Number for the label
271 * @return {Object} Filter data
272 */
273 mw.rcfilters.Controller.prototype._createFilterDataFromNumber = function ( num, numForDisplay ) {
274 return {
275 name: String( num ),
276 label: mw.language.convertNumber( numForDisplay )
277 };
278 };
279
280 /**
281 * Add an arbitrary values to groups that allow arbitrary values
282 *
283 * @param {Object} groupData Group data
284 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
285 */
286 mw.rcfilters.Controller.prototype.addNumberValuesToGroup = function ( groupData, arbitraryValues ) {
287 var controller = this,
288 normalizeWithinRange = function ( range, val ) {
289 if ( val < range.min ) {
290 return range.min; // Min
291 } else if ( val >= range.max ) {
292 return range.max; // Max
293 }
294 return val;
295 };
296
297 arbitraryValues = Array.isArray( arbitraryValues ) ? arbitraryValues : [ arbitraryValues ];
298
299 // Normalize the arbitrary values and the default value for a range
300 if ( groupData.range ) {
301 arbitraryValues = arbitraryValues.map( function ( val ) {
302 return normalizeWithinRange( groupData.range, val );
303 } );
304
305 // Normalize the default, since that's user defined
306 if ( groupData.default !== undefined ) {
307 groupData.default = String( normalizeWithinRange( groupData.range, groupData.default ) );
308 }
309 }
310
311 // This is only true for single_option group
312 // We assume these are the only groups that will allow for
313 // arbitrary, since it doesn't make any sense for the other
314 // groups.
315 arbitraryValues.forEach( function ( val ) {
316 if (
317 // If the group allows for arbitrary data
318 groupData.allowArbitrary &&
319 // and it is single_option (or string_options, but we
320 // don't have cases of those yet, nor do we plan to)
321 groupData.type === 'single_option' &&
322 // and, if there is a validate method and it passes on
323 // the data
324 ( !groupData.validate || groupData.validate( val ) ) &&
325 // but if that value isn't already in the definition
326 groupData.filters
327 .map( function ( filterData ) {
328 return String( filterData.name );
329 } )
330 .indexOf( String( val ) ) === -1
331 ) {
332 // Add the filter information
333 groupData.filters.push( controller._createFilterDataFromNumber(
334 val,
335 groupData.numToLabelFunc ?
336 groupData.numToLabelFunc( val ) :
337 val
338 ) );
339
340 // If there's a sort function set up, re-sort the values
341 if ( groupData.sortFunc ) {
342 groupData.filters.sort( groupData.sortFunc );
343 }
344 }
345 } );
346 };
347
348 /**
349 * Switch the view of the filters model
350 *
351 * @param {string} view Requested view
352 */
353 mw.rcfilters.Controller.prototype.switchView = function ( view ) {
354 this.filtersModel.switchView( view );
355 };
356
357 /**
358 * Reset to default filters
359 */
360 mw.rcfilters.Controller.prototype.resetToDefaults = function () {
361 this.uriProcessor.updateModelBasedOnQuery( this._getDefaultParams() );
362
363 this.updateChangesList();
364 };
365
366 /**
367 * Empty all selected filters
368 */
369 mw.rcfilters.Controller.prototype.emptyFilters = function () {
370 var highlightedFilterNames = this.filtersModel
371 .getHighlightedItems()
372 .map( function ( filterItem ) { return { name: filterItem.getName() }; } );
373
374 this.filtersModel.emptyAllFilters();
375 this.filtersModel.clearAllHighlightColors();
376 // Check all filter interactions
377 this.filtersModel.reassessFilterInteractions();
378
379 this.updateChangesList();
380
381 if ( highlightedFilterNames ) {
382 this._trackHighlight( 'clearAll', highlightedFilterNames );
383 }
384 };
385
386 /**
387 * Update the selected state of a filter
388 *
389 * @param {string} filterName Filter name
390 * @param {boolean} [isSelected] Filter selected state
391 */
392 mw.rcfilters.Controller.prototype.toggleFilterSelect = function ( filterName, isSelected ) {
393 var filterItem = this.filtersModel.getItemByName( filterName );
394
395 if ( !filterItem ) {
396 // If no filter was found, break
397 return;
398 }
399
400 isSelected = isSelected === undefined ? !filterItem.isSelected() : isSelected;
401
402 if ( filterItem.isSelected() !== isSelected ) {
403 this.filtersModel.toggleFilterSelected( filterName, isSelected );
404
405 this.updateChangesList();
406
407 // Check filter interactions
408 this.filtersModel.reassessFilterInteractions( filterItem );
409 }
410 };
411
412 /**
413 * Clear both highlight and selection of a filter
414 *
415 * @param {string} filterName Name of the filter item
416 */
417 mw.rcfilters.Controller.prototype.clearFilter = function ( filterName ) {
418 var filterItem = this.filtersModel.getItemByName( filterName ),
419 isHighlighted = filterItem.isHighlighted();
420
421 if ( filterItem.isSelected() || isHighlighted ) {
422 this.filtersModel.clearHighlightColor( filterName );
423 this.filtersModel.toggleFilterSelected( filterName, false );
424 this.updateChangesList();
425 this.filtersModel.reassessFilterInteractions( filterItem );
426
427 // Log filter grouping
428 this.trackFilterGroupings( 'removefilter' );
429 }
430
431 if ( isHighlighted ) {
432 this._trackHighlight( 'clear', filterName );
433 }
434 };
435
436 /**
437 * Toggle the highlight feature on and off
438 */
439 mw.rcfilters.Controller.prototype.toggleHighlight = function () {
440 this.filtersModel.toggleHighlight();
441 this._updateURL();
442
443 if ( this.filtersModel.isHighlightEnabled() ) {
444 mw.hook( 'RcFilters.highlight.enable' ).fire();
445 }
446 };
447
448 /**
449 * Toggle the namespaces inverted feature on and off
450 */
451 mw.rcfilters.Controller.prototype.toggleInvertedNamespaces = function () {
452 this.filtersModel.toggleInvertedNamespaces();
453
454 if (
455 this.filtersModel.getFiltersByView( 'namespaces' )
456 .filter( function ( filterItem ) {
457 return filterItem.isSelected();
458 } )
459 .length
460 ) {
461 // Only re-fetch results if there are namespace items that are actually selected
462 this.updateChangesList();
463 }
464 };
465
466 /**
467 * Set the highlight color for a filter item
468 *
469 * @param {string} filterName Name of the filter item
470 * @param {string} color Selected color
471 */
472 mw.rcfilters.Controller.prototype.setHighlightColor = function ( filterName, color ) {
473 this.filtersModel.setHighlightColor( filterName, color );
474 this._updateURL();
475 this._trackHighlight( 'set', { name: filterName, color: color } );
476 };
477
478 /**
479 * Clear highlight for a filter item
480 *
481 * @param {string} filterName Name of the filter item
482 */
483 mw.rcfilters.Controller.prototype.clearHighlightColor = function ( filterName ) {
484 this.filtersModel.clearHighlightColor( filterName );
485 this._updateURL();
486 this._trackHighlight( 'clear', filterName );
487 };
488
489 /**
490 * Enable or disable live updates.
491 * @param {boolean} enable True to enable, false to disable
492 */
493 mw.rcfilters.Controller.prototype.toggleLiveUpdate = function ( enable ) {
494 this.changesListModel.toggleLiveUpdate( enable );
495 if ( this.changesListModel.getLiveUpdate() && this.changesListModel.getNewChangesExist() ) {
496 this.updateChangesList( null, this.LIVE_UPDATE );
497 }
498 };
499
500 /**
501 * Set a timeout for the next live update.
502 * @private
503 */
504 mw.rcfilters.Controller.prototype._scheduleLiveUpdate = function () {
505 setTimeout( this._doLiveUpdate.bind( this ), 3000 );
506 };
507
508 /**
509 * Perform a live update.
510 * @private
511 */
512 mw.rcfilters.Controller.prototype._doLiveUpdate = function () {
513 if ( !this._shouldCheckForNewChanges() ) {
514 // skip this turn and check back later
515 this._scheduleLiveUpdate();
516 return;
517 }
518
519 this._checkForNewChanges()
520 .then( function ( data ) {
521 if ( !this._shouldCheckForNewChanges() ) {
522 // by the time the response is received,
523 // it may not be appropriate anymore
524 return;
525 }
526
527 if ( data.changes !== 'NO_RESULTS' ) {
528 if ( this.changesListModel.getLiveUpdate() ) {
529 return this.updateChangesList( null, this.LIVE_UPDATE );
530 } else {
531 this.changesListModel.setNewChangesExist( true );
532 }
533 }
534 }.bind( this ) )
535 .always( this._scheduleLiveUpdate.bind( this ) );
536 };
537
538 /**
539 * @return {boolean} It's appropriate to check for new changes now
540 * @private
541 */
542 mw.rcfilters.Controller.prototype._shouldCheckForNewChanges = function () {
543 var liveUpdateFeatureFlag = mw.config.get( 'wgStructuredChangeFiltersEnableLiveUpdate' ) ||
544 new mw.Uri().query.liveupdate;
545
546 return !document.hidden &&
547 !this.filtersModel.hasConflict() &&
548 !this.changesListModel.getNewChangesExist() &&
549 !this.updatingChangesList &&
550 liveUpdateFeatureFlag;
551 };
552
553 /**
554 * Check if new changes, newer than those currently shown, are available
555 *
556 * @return {jQuery.Promise} Promise object that resolves after trying
557 * to fetch 1 change newer than the last known 'from' parameter value
558 *
559 * @private
560 */
561 mw.rcfilters.Controller.prototype._checkForNewChanges = function () {
562 return this._fetchChangesList(
563 'liveUpdate',
564 {
565 limit: 1,
566 from: this.changesListModel.getNextFrom()
567 }
568 );
569 };
570
571 /**
572 * Show the new changes
573 *
574 * @return {jQuery.Promise} Promise object that resolves after
575 * fetching and showing the new changes
576 */
577 mw.rcfilters.Controller.prototype.showNewChanges = function () {
578 return this.updateChangesList( null, this.SHOW_NEW_CHANGES );
579 };
580
581 /**
582 * Save the current model state as a saved query
583 *
584 * @param {string} [label] Label of the saved query
585 * @param {boolean} [setAsDefault=false] This query should be set as the default
586 */
587 mw.rcfilters.Controller.prototype.saveCurrentQuery = function ( label, setAsDefault ) {
588 var queryID,
589 highlightedItems = {},
590 highlightEnabled = this.filtersModel.isHighlightEnabled(),
591 selectedState = this.filtersModel.getSelectedState();
592
593 // Prepare highlights
594 this.filtersModel.getHighlightedItems().forEach( function ( item ) {
595 highlightedItems[ item.getName() ] = highlightEnabled ?
596 item.getHighlightColor() : null;
597 } );
598 // These are filter states; highlight is stored as boolean
599 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
600
601 // Delete all sticky filters
602 this._deleteStickyValuesFromFilterState( selectedState );
603
604 // Add item
605 queryID = this.savedQueriesModel.addNewQuery(
606 label || mw.msg( 'rcfilters-savedqueries-defaultlabel' ),
607 {
608 filters: selectedState,
609 highlights: highlightedItems,
610 invert: this.filtersModel.areNamespacesInverted()
611 }
612 );
613
614 if ( setAsDefault ) {
615 this.savedQueriesModel.setDefault( queryID );
616 }
617
618 // Save item
619 this._saveSavedQueries();
620 };
621
622 /**
623 * Remove a saved query
624 *
625 * @param {string} queryID Query id
626 */
627 mw.rcfilters.Controller.prototype.removeSavedQuery = function ( queryID ) {
628 this.savedQueriesModel.removeQuery( queryID );
629
630 this._saveSavedQueries();
631 };
632
633 /**
634 * Rename a saved query
635 *
636 * @param {string} queryID Query id
637 * @param {string} newLabel New label for the query
638 */
639 mw.rcfilters.Controller.prototype.renameSavedQuery = function ( queryID, newLabel ) {
640 var queryItem = this.savedQueriesModel.getItemByID( queryID );
641
642 if ( queryItem ) {
643 queryItem.updateLabel( newLabel );
644 }
645 this._saveSavedQueries();
646 };
647
648 /**
649 * Set a saved query as default
650 *
651 * @param {string} queryID Query Id. If null is given, default
652 * query is reset.
653 */
654 mw.rcfilters.Controller.prototype.setDefaultSavedQuery = function ( queryID ) {
655 this.savedQueriesModel.setDefault( queryID );
656 this._saveSavedQueries();
657 };
658
659 /**
660 * Load a saved query
661 *
662 * @param {string} queryID Query id
663 */
664 mw.rcfilters.Controller.prototype.applySavedQuery = function ( queryID ) {
665 var data, highlights,
666 queryItem = this.savedQueriesModel.getItemByID( queryID ),
667 currentMatchingQuery = this.findQueryMatchingCurrentState();
668
669 if (
670 queryItem &&
671 (
672 // If there's already a query, don't reload it
673 // if it's the same as the one that already exists
674 !currentMatchingQuery ||
675 currentMatchingQuery.getID() !== queryItem.getID()
676 )
677 ) {
678 data = queryItem.getData();
679 highlights = data.highlights;
680
681 // Backwards compatibility; initial version mispelled 'highlight' with 'highlights'
682 highlights.highlight = highlights.highlights || highlights.highlight;
683
684 // Update model state from filters
685 this.filtersModel.toggleFiltersSelected(
686 // Merge filters with sticky values
687 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
688 );
689
690 // Update namespace inverted property
691 this.filtersModel.toggleInvertedNamespaces( !!Number( data.invert ) );
692
693 // Update highlight state
694 this.filtersModel.toggleHighlight( !!Number( highlights.highlight ) );
695 this.filtersModel.getItems().forEach( function ( filterItem ) {
696 var color = highlights[ filterItem.getName() ];
697 if ( color ) {
698 filterItem.setHighlightColor( color );
699 } else {
700 filterItem.clearHighlightColor();
701 }
702 } );
703
704 // Check all filter interactions
705 this.filtersModel.reassessFilterInteractions();
706
707 this.updateChangesList();
708
709 // Log filter grouping
710 this.trackFilterGroupings( 'savedfilters' );
711 }
712 };
713
714 /**
715 * Check whether the current filter and highlight state exists
716 * in the saved queries model.
717 *
718 * @return {boolean} Query exists
719 */
720 mw.rcfilters.Controller.prototype.findQueryMatchingCurrentState = function () {
721 var highlightedItems = {},
722 selectedState = this.filtersModel.getSelectedState();
723
724 // Prepare highlights of the current query
725 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
726 highlightedItems[ item.getName() ] = item.getHighlightColor();
727 } );
728 highlightedItems.highlight = this.filtersModel.isHighlightEnabled();
729
730 // Remove sticky filters
731 this._deleteStickyValuesFromFilterState( selectedState );
732
733 return this.savedQueriesModel.findMatchingQuery(
734 {
735 filters: selectedState,
736 highlights: highlightedItems,
737 invert: this.filtersModel.areNamespacesInverted()
738 }
739 );
740 };
741
742 /**
743 * Delete sticky filters from given object
744 *
745 * @param {Object} filterState Filter state
746 */
747 mw.rcfilters.Controller.prototype._deleteStickyValuesFromFilterState = function ( filterState ) {
748 // Remove sticky filters
749 $.each( this.filtersModel.getStickyFiltersState(), function ( filterName ) {
750 delete filterState[ filterName ];
751 } );
752 };
753
754 /**
755 * Get an object representing the base state of parameters
756 * and highlights.
757 *
758 * This is meant to make sure that the saved queries that are
759 * in memory are always the same structure as what we would get
760 * by calling the current model's "getSelectedState" and by checking
761 * highlight items.
762 *
763 * In cases where a user saved a query when the system had a certain
764 * set of filters, and then a filter was added to the system, we want
765 * to make sure that the stored queries can still be comparable to
766 * the current state, which means that we need the base state for
767 * two operations:
768 *
769 * - Saved queries are stored in "minimal" view (only changed filters
770 * are stored); When we initialize the system, we merge each minimal
771 * query with the base state (using 'getNormalizedFilters') so all
772 * saved queries have the exact same structure as what we would get
773 * by checking the getSelectedState of the filter.
774 * - When we save the queries, we minimize the object to only represent
775 * whatever has actually changed, rather than store the entire
776 * object. To check what actually is different so we can store it,
777 * we need to obtain a base state to compare against, this is
778 * what #_getMinimalFilterList does
779 */
780 mw.rcfilters.Controller.prototype._buildBaseFilterState = function () {
781 var defaultParams = this.filtersModel.getDefaultParams(),
782 highlightedItems = {};
783
784 // Prepare highlights
785 this.filtersModel.getItemsSupportingHighlights().forEach( function ( item ) {
786 highlightedItems[ item.getName() ] = null;
787 } );
788 highlightedItems.highlight = false;
789
790 this.baseFilterState = {
791 filters: this.filtersModel.getFiltersFromParameters( defaultParams ),
792 highlights: highlightedItems,
793 invert: false
794 };
795 };
796
797 /**
798 * Get an object representing the base filter state of both
799 * filters and highlights. The structure is similar to what we use
800 * to store each query in the saved queries object:
801 * {
802 * filters: {
803 * filterName: (bool)
804 * },
805 * highlights: {
806 * filterName: (string|null)
807 * }
808 * }
809 *
810 * @return {Object} Object representing the base state of
811 * parameters and highlights
812 */
813 mw.rcfilters.Controller.prototype._getBaseFilterState = function () {
814 return this.baseFilterState;
815 };
816
817 /**
818 * Get an object that holds only the parameters and highlights that have
819 * values different than the base default value.
820 *
821 * This is the reverse of the normalization we do initially on loading and
822 * initializing the saved queries model.
823 *
824 * @param {Object} valuesObject Object representing the state of both
825 * filters and highlights in its normalized version, to be minimized.
826 * @return {Object} Minimal filters and highlights list
827 */
828 mw.rcfilters.Controller.prototype._getMinimalFilterList = function ( valuesObject ) {
829 var result = { filters: {}, highlights: {} },
830 baseState = this._getBaseFilterState();
831
832 // XOR results
833 $.each( valuesObject.filters, function ( name, value ) {
834 if ( baseState.filters !== undefined && baseState.filters[ name ] !== value ) {
835 result.filters[ name ] = value;
836 }
837 } );
838
839 $.each( valuesObject.highlights, function ( name, value ) {
840 if ( baseState.highlights !== undefined && baseState.highlights[ name ] !== value ) {
841 result.highlights[ name ] = value;
842 }
843 } );
844
845 return result;
846 };
847
848 /**
849 * Save the current state of the saved queries model with all
850 * query item representation in the user settings.
851 */
852 mw.rcfilters.Controller.prototype._saveSavedQueries = function () {
853 var stringified,
854 state = this.savedQueriesModel.getState(),
855 controller = this;
856
857 // Minimize before save
858 $.each( state.queries, function ( queryID, info ) {
859 state.queries[ queryID ].data = controller._getMinimalFilterList( info.data );
860 } );
861
862 // Stringify state
863 stringified = JSON.stringify( state );
864
865 if ( stringified.length > 65535 ) {
866 // Sanity check, since the preference can only hold that.
867 return;
868 }
869
870 // Save the preference
871 new mw.Api().saveOption( 'rcfilters-saved-queries', stringified );
872 // Update the preference for this session
873 mw.user.options.set( 'rcfilters-saved-queries', stringified );
874 };
875
876 /**
877 * Update sticky preferences with current model state
878 */
879 mw.rcfilters.Controller.prototype.updateStickyPreferences = function () {
880 // Update default sticky values with selected, whether they came from
881 // the initial defaults or from the URL value that is being normalized
882 this.updateDaysDefault( this.filtersModel.getGroup( 'days' ).getSelectedItems()[ 0 ].getParamName() );
883 this.updateLimitDefault( this.filtersModel.getGroup( 'limit' ).getSelectedItems()[ 0 ].getParamName() );
884
885 // TODO: Make these automatic by having the model go over sticky
886 // items and update their default values automatically
887 };
888
889 /**
890 * Update the limit default value
891 *
892 * param {number} newValue New value
893 */
894 mw.rcfilters.Controller.prototype.updateLimitDefault = function ( /* newValue */ ) {
895 // HACK: Temporarily remove this from being sticky
896 // See T172156
897
898 /*
899 if ( !$.isNumeric( newValue ) ) {
900 return;
901 }
902
903 newValue = Number( newValue );
904
905 if ( mw.user.options.get( 'rcfilters-rclimit' ) !== newValue ) {
906 // Save the preference
907 new mw.Api().saveOption( 'rcfilters-rclimit', newValue );
908 // Update the preference for this session
909 mw.user.options.set( 'rcfilters-rclimit', newValue );
910 }
911 */
912 return;
913 };
914
915 /**
916 * Update the days default value
917 *
918 * param {number} newValue New value
919 */
920 mw.rcfilters.Controller.prototype.updateDaysDefault = function ( /* newValue */ ) {
921 // HACK: Temporarily remove this from being sticky
922 // See T172156
923
924 /*
925 if ( !$.isNumeric( newValue ) ) {
926 return;
927 }
928
929 newValue = Number( newValue );
930
931 if ( mw.user.options.get( 'rcdays' ) !== newValue ) {
932 // Save the preference
933 new mw.Api().saveOption( 'rcdays', newValue );
934 // Update the preference for this session
935 mw.user.options.set( 'rcdays', newValue );
936 }
937 */
938 return;
939 };
940
941 /**
942 * Update the group by page default value
943 *
944 * @param {number} newValue New value
945 */
946 mw.rcfilters.Controller.prototype.updateGroupByPageDefault = function ( newValue ) {
947 if ( !$.isNumeric( newValue ) ) {
948 return;
949 }
950
951 newValue = Number( newValue );
952
953 if ( mw.user.options.get( 'usenewrc' ) !== newValue ) {
954 // Save the preference
955 new mw.Api().saveOption( 'usenewrc', newValue );
956 // Update the preference for this session
957 mw.user.options.set( 'usenewrc', newValue );
958 }
959 };
960
961 /**
962 * Synchronize the URL with the current state of the filters
963 * without adding an history entry.
964 */
965 mw.rcfilters.Controller.prototype.replaceUrl = function () {
966 mw.rcfilters.UriProcessor.static.replaceState( this._getUpdatedUri() );
967 };
968
969 /**
970 * Update filter state (selection and highlighting) based
971 * on current URL values.
972 *
973 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
974 * list based on the updated model.
975 */
976 mw.rcfilters.Controller.prototype.updateStateFromUrl = function ( fetchChangesList ) {
977 fetchChangesList = fetchChangesList === undefined ? true : !!fetchChangesList;
978
979 this.uriProcessor.updateModelBasedOnQuery( new mw.Uri().query );
980
981 // Update the sticky preferences, in case we received a value
982 // from the URL
983 this.updateStickyPreferences();
984
985 // Only update and fetch new results if it is requested
986 if ( fetchChangesList ) {
987 this.updateChangesList();
988 }
989 };
990
991 /**
992 * Update the list of changes and notify the model
993 *
994 * @param {Object} [params] Extra parameters to add to the API call
995 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges'
996 * @return {jQuery.Promise} Promise that is resolved when the update is complete
997 */
998 mw.rcfilters.Controller.prototype.updateChangesList = function ( params, updateMode ) {
999 updateMode = updateMode === undefined ? this.FILTER_CHANGE : updateMode;
1000
1001 if ( updateMode === this.FILTER_CHANGE ) {
1002 this._updateURL( params );
1003 }
1004 if ( updateMode === this.FILTER_CHANGE || updateMode === this.SHOW_NEW_CHANGES ) {
1005 this.changesListModel.invalidate();
1006 }
1007 this.changesListModel.setNewChangesExist( false );
1008 this.updatingChangesList = true;
1009 return this._fetchChangesList()
1010 .then(
1011 // Success
1012 function ( pieces ) {
1013 var $changesListContent = pieces.changes,
1014 $fieldset = pieces.fieldset;
1015 this.changesListModel.update(
1016 $changesListContent,
1017 $fieldset,
1018 false,
1019 updateMode === this.SHOW_NEW_CHANGES
1020 );
1021 }.bind( this )
1022 // Do nothing for failure
1023 )
1024 .always( function () {
1025 this.updatingChangesList = false;
1026 }.bind( this ) );
1027 };
1028
1029 /**
1030 * Get an object representing the default parameter state, whether
1031 * it is from the model defaults or from the saved queries.
1032 *
1033 * @return {Object} Default parameters
1034 */
1035 mw.rcfilters.Controller.prototype._getDefaultParams = function () {
1036 var data, queryHighlights,
1037 savedParams = {},
1038 savedHighlights = {},
1039 defaultSavedQueryItem = this.savedQueriesModel.getItemByID( this.savedQueriesModel.getDefault() );
1040
1041 if ( defaultSavedQueryItem ) {
1042 data = defaultSavedQueryItem.getData();
1043
1044 queryHighlights = data.highlights || {};
1045 savedParams = this.filtersModel.getParametersFromFilters(
1046 // Merge filters with sticky values
1047 $.extend( true, {}, data.filters, this.filtersModel.getStickyFiltersState() )
1048 );
1049
1050 // Translate highlights to parameters
1051 savedHighlights.highlight = String( Number( queryHighlights.highlight ) );
1052 $.each( queryHighlights, function ( filterName, color ) {
1053 if ( filterName !== 'highlights' ) {
1054 savedHighlights[ filterName + '_color' ] = color;
1055 }
1056 } );
1057
1058 return $.extend( true, {}, savedParams, savedHighlights );
1059 }
1060
1061 return this.filtersModel.getDefaultParams();
1062 };
1063
1064 /**
1065 * Update the URL of the page to reflect current filters
1066 *
1067 * This should not be called directly from outside the controller.
1068 * If an action requires changing the URL, it should either use the
1069 * highlighting actions below, or call #updateChangesList which does
1070 * the uri corrections already.
1071 *
1072 * @param {Object} [params] Extra parameters to add to the API call
1073 */
1074 mw.rcfilters.Controller.prototype._updateURL = function ( params ) {
1075 var currentUri = new mw.Uri(),
1076 updatedUri = this._getUpdatedUri();
1077
1078 updatedUri.extend( params || {} );
1079
1080 if (
1081 this.uriProcessor.getVersion( currentUri.query ) !== 2 ||
1082 this.uriProcessor.isNewState( currentUri.query, updatedUri.query )
1083 ) {
1084 mw.rcfilters.UriProcessor.static.replaceState( updatedUri );
1085 }
1086 };
1087
1088 /**
1089 * Get an updated mw.Uri object based on the model state
1090 *
1091 * @return {mw.Uri} Updated Uri
1092 */
1093 mw.rcfilters.Controller.prototype._getUpdatedUri = function () {
1094 var uri = new mw.Uri();
1095
1096 // Minimize url
1097 uri.query = this.uriProcessor.minimizeQuery(
1098 $.extend(
1099 true,
1100 {},
1101 // We want to retain unrecognized params
1102 // The uri params from model will override
1103 // any recognized value in the current uri
1104 // query, retain unrecognized params, and
1105 // the result will then be minimized
1106 uri.query,
1107 this.uriProcessor.getUriParametersFromModel(),
1108 { urlversion: '2' }
1109 )
1110 );
1111
1112 return uri;
1113 };
1114
1115 /**
1116 * Fetch the list of changes from the server for the current filters
1117 *
1118 * @param {string} [counterId='updateChangesList'] Id for this request. To allow concurrent requests
1119 * not to invalidate each other.
1120 * @param {Object} [params={}] Parameters to add to the query
1121 *
1122 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1123 * or with a string denoting no results.
1124 */
1125 mw.rcfilters.Controller.prototype._fetchChangesList = function ( counterId, params ) {
1126 var uri = this._getUpdatedUri(),
1127 stickyParams = this.filtersModel.getStickyParams(),
1128 requestId,
1129 latestRequest;
1130
1131 counterId = counterId || 'updateChangesList';
1132 params = params || {};
1133
1134 uri.extend( params );
1135
1136 this.requestCounter[ counterId ] = this.requestCounter[ counterId ] || 0;
1137 requestId = ++this.requestCounter[ counterId ];
1138 latestRequest = function () {
1139 return requestId === this.requestCounter[ counterId ];
1140 }.bind( this );
1141
1142 // Sticky parameters override the URL params
1143 // this is to make sure that whether we represent
1144 // the sticky params in the URL or not (they may
1145 // be normalized out) the sticky parameters are
1146 // always being sent to the server with their
1147 // current/default values
1148 uri.extend( stickyParams );
1149
1150 return $.ajax( uri.toString(), { contentType: 'html' } )
1151 .then(
1152 // Success
1153 function ( html ) {
1154 var $parsed;
1155 if ( !latestRequest() ) {
1156 return $.Deferred().reject();
1157 }
1158
1159 $parsed = $( $.parseHTML( html ) );
1160
1161 return {
1162 // Changes list
1163 changes: $parsed.find( '.mw-changeslist' ).first().contents(),
1164 // Fieldset
1165 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1166 };
1167 },
1168 // Failure
1169 function ( responseObj ) {
1170 var $parsed;
1171
1172 if ( !latestRequest() ) {
1173 return $.Deferred().reject();
1174 }
1175
1176 $parsed = $( $.parseHTML( responseObj.responseText ) );
1177
1178 // Force a resolve state to this promise
1179 return $.Deferred().resolve( {
1180 changes: 'NO_RESULTS',
1181 fieldset: $parsed.find( 'fieldset.rcoptions' ).first()
1182 } ).promise();
1183 }
1184 );
1185 };
1186
1187 /**
1188 * Track usage of highlight feature
1189 *
1190 * @param {string} action
1191 * @param {Array|Object|string} filters
1192 */
1193 mw.rcfilters.Controller.prototype._trackHighlight = function ( action, filters ) {
1194 filters = typeof filters === 'string' ? { name: filters } : filters;
1195 filters = !Array.isArray( filters ) ? [ filters ] : filters;
1196 mw.track(
1197 'event.ChangesListHighlights',
1198 {
1199 action: action,
1200 filters: filters,
1201 userId: mw.user.getId()
1202 }
1203 );
1204 };
1205
1206 /**
1207 * Track filter grouping usage
1208 *
1209 * @param {string} action Action taken
1210 */
1211 mw.rcfilters.Controller.prototype.trackFilterGroupings = function ( action ) {
1212 var controller = this,
1213 rightNow = new Date().getTime(),
1214 randomIdentifier = String( mw.user.sessionId() ) + String( rightNow ) + String( Math.random() ),
1215 // Get all current filters
1216 filters = this.filtersModel.getSelectedItems().map( function ( item ) {
1217 return item.getName();
1218 } );
1219
1220 action = action || 'filtermenu';
1221
1222 // Check if these filters were the ones we just logged previously
1223 // (Don't log the same grouping twice, in case the user opens/closes)
1224 // the menu without action, or with the same result
1225 if (
1226 // Only log if the two arrays are different in size
1227 filters.length !== this.prevLoggedItems.length ||
1228 // Or if any filters are not the same as the cached filters
1229 filters.some( function ( filterName ) {
1230 return controller.prevLoggedItems.indexOf( filterName ) === -1;
1231 } ) ||
1232 // Or if any cached filters are not the same as given filters
1233 this.prevLoggedItems.some( function ( filterName ) {
1234 return filters.indexOf( filterName ) === -1;
1235 } )
1236 ) {
1237 filters.forEach( function ( filterName ) {
1238 mw.track(
1239 'event.ChangesListFilterGrouping',
1240 {
1241 action: action,
1242 groupIdentifier: randomIdentifier,
1243 filter: filterName,
1244 userId: mw.user.getId()
1245 }
1246 );
1247 } );
1248
1249 // Cache the filter names
1250 this.prevLoggedItems = filters;
1251 }
1252 };
1253 }( mediaWiki, jQuery ) );