Merge "user: Allow "CAS update failed" exceptions to be normalised"
[lhc/web/wiklou.git] / resources / src / mediawiki.rcfilters / dm / mw.rcfilters.dm.SavedQueriesModel.js
1 /* eslint-disable no-restricted-properties */
2 ( function () {
3 /**
4 * View model for saved queries
5 *
6 * @class
7 * @mixins OO.EventEmitter
8 * @mixins OO.EmitterList
9 *
10 * @constructor
11 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters model
12 * @param {Object} [config] Configuration options
13 * @cfg {string} [default] Default query ID
14 */
15 mw.rcfilters.dm.SavedQueriesModel = function MwRcfiltersDmSavedQueriesModel( filtersModel, config ) {
16 config = config || {};
17
18 // Mixin constructor
19 OO.EventEmitter.call( this );
20 OO.EmitterList.call( this );
21
22 this.default = config.default;
23 this.filtersModel = filtersModel;
24 this.converted = false;
25
26 // Events
27 this.aggregate( { update: 'itemUpdate' } );
28 };
29
30 /* Initialization */
31
32 OO.initClass( mw.rcfilters.dm.SavedQueriesModel );
33 OO.mixinClass( mw.rcfilters.dm.SavedQueriesModel, OO.EventEmitter );
34 OO.mixinClass( mw.rcfilters.dm.SavedQueriesModel, OO.EmitterList );
35
36 /* Events */
37
38 /**
39 * @event initialize
40 *
41 * Model is initialized
42 */
43
44 /**
45 * @event itemUpdate
46 * @param {mw.rcfilters.dm.SavedQueryItemModel} Changed item
47 *
48 * An item has changed
49 */
50
51 /**
52 * @event default
53 * @param {string} New default ID
54 *
55 * The default has changed
56 */
57
58 /* Methods */
59
60 /**
61 * Initialize the saved queries model by reading it from the user's settings.
62 * The structure of the saved queries is:
63 * {
64 * version: (string) Version number; if version 2, the query represents
65 * parameters. Otherwise, the older version represented filters
66 * and needs to be readjusted,
67 * default: (string) Query ID
68 * queries:{
69 * query_id_1: {
70 * data:{
71 * filters: (Object) Minimal definition of the filters
72 * highlights: (Object) Definition of the highlights
73 * },
74 * label: (optional) Name of this query
75 * }
76 * }
77 * }
78 *
79 * @param {Object} [savedQueries] An object with the saved queries with
80 * the above structure.
81 * @fires initialize
82 */
83 mw.rcfilters.dm.SavedQueriesModel.prototype.initialize = function ( savedQueries ) {
84 var model = this;
85
86 savedQueries = savedQueries || {};
87
88 this.clearItems();
89 this.default = null;
90 this.converted = false;
91
92 if ( savedQueries.version !== '2' ) {
93 // Old version dealt with filter names. We need to migrate to the new structure
94 // The new structure:
95 // {
96 // version: (string) '2',
97 // default: (string) Query ID,
98 // queries: {
99 // query_id: {
100 // label: (string) Name of the query
101 // data: {
102 // params: (object) Representing all the parameter states
103 // highlights: (object) Representing all the filter highlight states
104 // }
105 // }
106 // }
107 $.each( savedQueries.queries || {}, function ( id, obj ) {
108 if ( obj.data && obj.data.filters ) {
109 obj.data = model.convertToParameters( obj.data );
110 }
111 } );
112
113 this.converted = true;
114 savedQueries.version = '2';
115 }
116
117 // Initialize the query items
118 $.each( savedQueries.queries || {}, function ( id, obj ) {
119 var normalizedData = obj.data,
120 isDefault = String( savedQueries.default ) === String( id );
121
122 if ( normalizedData && normalizedData.params ) {
123 // Backwards-compat fix: Remove sticky parameters from
124 // the given data, if they exist
125 normalizedData.params = model.filtersModel.removeStickyParams( normalizedData.params );
126
127 // Correct the invert state for effective selection
128 if ( normalizedData.params.invert && !normalizedData.params.namespace ) {
129 delete normalizedData.params.invert;
130 }
131
132 model.cleanupHighlights( normalizedData );
133
134 id = String( id );
135
136 // Skip the addNewQuery method because we don't want to unnecessarily manipulate
137 // the given saved queries unless we literally intend to (like in backwards compat fixes)
138 // And the addNewQuery method also uses a minimization routine that checks for the
139 // validity of items and minimizes the query. This isn't necessary for queries loaded
140 // from the backend, and has the risk of removing values if they're temporarily
141 // invalid (example: if we temporarily removed a cssClass from a filter in the backend)
142 model.addItems( [
143 new mw.rcfilters.dm.SavedQueryItemModel(
144 id,
145 obj.label,
146 normalizedData,
147 { 'default': isDefault }
148 )
149 ] );
150
151 if ( isDefault ) {
152 model.default = id;
153 }
154 }
155 } );
156
157 this.emit( 'initialize' );
158 };
159
160 /**
161 * Clean up highlight parameters.
162 * 'highlight' used to be stored, it's not inferred based on the presence of absence of
163 * filter colors.
164 *
165 * @param {Object} data Saved query data
166 */
167 mw.rcfilters.dm.SavedQueriesModel.prototype.cleanupHighlights = function ( data ) {
168 if (
169 data.params.highlight === '0' &&
170 data.highlights && Object.keys( data.highlights ).length
171 ) {
172 data.highlights = {};
173 }
174 delete data.params.highlight;
175 };
176
177 /**
178 * Convert from representation of filters to representation of parameters
179 *
180 * @param {Object} data Query data
181 * @return {Object} New converted query data
182 */
183 mw.rcfilters.dm.SavedQueriesModel.prototype.convertToParameters = function ( data ) {
184 var newData = {},
185 defaultFilters = this.filtersModel.getFiltersFromParameters( this.filtersModel.getDefaultParams() ),
186 fullFilterRepresentation = $.extend( true, {}, defaultFilters, data.filters ),
187 highlightEnabled = data.highlights.highlight;
188
189 delete data.highlights.highlight;
190
191 // Filters
192 newData.params = this.filtersModel.getMinimizedParamRepresentation(
193 this.filtersModel.getParametersFromFilters( fullFilterRepresentation )
194 );
195
196 // Highlights: appending _color to keys
197 newData.highlights = {};
198 $.each( data.highlights, function ( highlightedFilterName, value ) {
199 if ( value ) {
200 newData.highlights[ highlightedFilterName + '_color' ] = data.highlights[ highlightedFilterName ];
201 }
202 } );
203
204 // Add highlight
205 newData.params.highlight = String( Number( highlightEnabled || 0 ) );
206
207 return newData;
208 };
209
210 /**
211 * Add a query item
212 *
213 * @param {string} label Label for the new query
214 * @param {Object} fulldata Full data representation for the new query, combining highlights and filters
215 * @param {boolean} isDefault Item is default
216 * @param {string} [id] Query ID, if exists. If this isn't given, a random
217 * new ID will be created.
218 * @return {string} ID of the newly added query
219 */
220 mw.rcfilters.dm.SavedQueriesModel.prototype.addNewQuery = function ( label, fulldata, isDefault, id ) {
221 var normalizedData = { params: {}, highlights: {} },
222 highlightParamNames = Object.keys( this.filtersModel.getEmptyHighlightParameters() ),
223 randomID = String( id || ( new Date() ).getTime() ),
224 data = this.filtersModel.getMinimizedParamRepresentation( fulldata );
225
226 // Split highlight/params
227 $.each( data, function ( param, value ) {
228 if ( param !== 'highlight' && highlightParamNames.indexOf( param ) > -1 ) {
229 normalizedData.highlights[ param ] = value;
230 } else {
231 normalizedData.params[ param ] = value;
232 }
233 } );
234
235 // Correct the invert state for effective selection
236 if ( normalizedData.params.invert && !this.filtersModel.areNamespacesEffectivelyInverted() ) {
237 delete normalizedData.params.invert;
238 }
239
240 // Add item
241 this.addItems( [
242 new mw.rcfilters.dm.SavedQueryItemModel(
243 randomID,
244 label,
245 normalizedData,
246 { 'default': isDefault }
247 )
248 ] );
249
250 if ( isDefault ) {
251 this.setDefault( randomID );
252 }
253
254 return randomID;
255 };
256
257 /**
258 * Remove query from model
259 *
260 * @param {string} queryID Query ID
261 */
262 mw.rcfilters.dm.SavedQueriesModel.prototype.removeQuery = function ( queryID ) {
263 var query = this.getItemByID( queryID );
264
265 if ( query ) {
266 // Check if this item was the default
267 if ( String( this.getDefault() ) === String( queryID ) ) {
268 // Nulify the default
269 this.setDefault( null );
270 }
271
272 this.removeItems( [ query ] );
273 }
274 };
275
276 /**
277 * Get an item that matches the requested query
278 *
279 * @param {Object} fullQueryComparison Object representing all filters and highlights to compare
280 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
281 */
282 mw.rcfilters.dm.SavedQueriesModel.prototype.findMatchingQuery = function ( fullQueryComparison ) {
283 // Minimize before comparison
284 fullQueryComparison = this.filtersModel.getMinimizedParamRepresentation( fullQueryComparison );
285
286 // Correct the invert state for effective selection
287 if ( fullQueryComparison.invert && !this.filtersModel.areNamespacesEffectivelyInverted() ) {
288 delete fullQueryComparison.invert;
289 }
290
291 return this.getItems().filter( function ( item ) {
292 return OO.compare(
293 item.getCombinedData(),
294 fullQueryComparison
295 );
296 } )[ 0 ];
297 };
298
299 /**
300 * Get query by its identifier
301 *
302 * @param {string} queryID Query identifier
303 * @return {mw.rcfilters.dm.SavedQueryItemModel|undefined} Item matching
304 * the search. Undefined if not found.
305 */
306 mw.rcfilters.dm.SavedQueriesModel.prototype.getItemByID = function ( queryID ) {
307 return this.getItems().filter( function ( item ) {
308 return item.getID() === queryID;
309 } )[ 0 ];
310 };
311
312 /**
313 * Get the full data representation of the default query, if it exists
314 *
315 * @return {Object|null} Representation of the default params if exists.
316 * Null if default doesn't exist or if the user is not logged in.
317 */
318 mw.rcfilters.dm.SavedQueriesModel.prototype.getDefaultParams = function () {
319 return ( !mw.user.isAnon() && this.getItemParams( this.getDefault() ) ) || {};
320 };
321
322 /**
323 * Get a full parameter representation of an item data
324 *
325 * @param {Object} queryID Query ID
326 * @return {Object} Parameter representation
327 */
328 mw.rcfilters.dm.SavedQueriesModel.prototype.getItemParams = function ( queryID ) {
329 var item = this.getItemByID( queryID ),
330 data = item ? item.getData() : {};
331
332 return !$.isEmptyObject( data ) ? this.buildParamsFromData( data ) : {};
333 };
334
335 /**
336 * Build a full parameter representation given item data and model sticky values state
337 *
338 * @param {Object} data Item data
339 * @return {Object} Full param representation
340 */
341 mw.rcfilters.dm.SavedQueriesModel.prototype.buildParamsFromData = function ( data ) {
342 data = data || {};
343 // Return parameter representation
344 return this.filtersModel.getMinimizedParamRepresentation( $.extend( true, {},
345 data.params,
346 data.highlights
347 ) );
348 };
349
350 /**
351 * Get the object representing the state of the entire model and items
352 *
353 * @return {Object} Object representing the state of the model and items
354 */
355 mw.rcfilters.dm.SavedQueriesModel.prototype.getState = function () {
356 var obj = { queries: {}, version: '2' };
357
358 // Translate the items to the saved object
359 this.getItems().forEach( function ( item ) {
360 obj.queries[ item.getID() ] = item.getState();
361 } );
362
363 if ( this.getDefault() ) {
364 obj.default = this.getDefault();
365 }
366
367 return obj;
368 };
369
370 /**
371 * Set a default query. Null to unset default.
372 *
373 * @param {string} itemID Query identifier
374 * @fires default
375 */
376 mw.rcfilters.dm.SavedQueriesModel.prototype.setDefault = function ( itemID ) {
377 if ( this.default !== itemID ) {
378 this.default = itemID;
379
380 // Set for individual itens
381 this.getItems().forEach( function ( item ) {
382 item.toggleDefault( item.getID() === itemID );
383 } );
384
385 this.emit( 'default', itemID );
386 }
387 };
388
389 /**
390 * Get the default query ID
391 *
392 * @return {string} Default query identifier
393 */
394 mw.rcfilters.dm.SavedQueriesModel.prototype.getDefault = function () {
395 return this.default;
396 };
397
398 /**
399 * Check if the saved queries were converted
400 *
401 * @return {boolean} Saved queries were converted from the previous
402 * version to the new version
403 */
404 mw.rcfilters.dm.SavedQueriesModel.prototype.isConverted = function () {
405 return this.converted;
406 };
407 }() );