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