Debian Codegraph @

resources/src/mediawiki.widgets/MediaSearch/mw.widgets.MediaSearchWidget.js

raw symbols SCIP
1 /*!
2 * MediaWiki Widgets - MediaSearchWidget class.
3 *
4 * @copyright 2011-2016 VisualEditor Team and others; see AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7 ( function () {
8
9 /**
10 * @classdesc Media search widget.
11 *
12 * @class
13 * @extends OO.ui.SearchWidget
14 *
15 * @constructor
16 * @description Creates an mw.widgets.MediaSearchWidget object.
17 * @param {Object} [config] Configuration options
18 * @param {number} [size] Vertical size of thumbnails
19 */
20 mw.widgets.MediaSearchWidget = function MwWidgetsMediaSearchWidget( config ) {
21 // Configuration initialization
22 config = Object.assign( {
23 placeholder: mw.msg( 'mw-widgets-mediasearch-input-placeholder' )
24 }, config );
25
26 // Parent constructor
27 mw.widgets.MediaSearchWidget.super.call( this, config );
28
29 // Properties
30 this.providers = {};
31 this.lastQueryValue = '';
32
33 const queueConfig = {
34 limit: this.constructor.static.limit,
35 threshold: this.constructor.static.threshold
36 };
37 this.searchQueue = new mw.widgets.MediaSearchQueue( queueConfig );
38 this.userUploadsQueue = new mw.widgets.MediaUserUploadsQueue( queueConfig );
39 this.currentQueue = null;
40
41 this.queryTimeout = null;
42 this.itemCache = {};
43 this.promises = [];
44 this.$panels = config.$panels;
45
46 this.externalLinkUrlProtocolsRegExp = new RegExp(
47 '^(' + mw.config.get( 'wgUrlProtocols' ) + ')',
48 'i'
49 );
50
51 // Masonry fit properties
52 this.rows = [];
53 this.rowHeight = config.rowHeight || 200;
54 this.layoutQueue = [];
55 this.numItems = 0;
56 this.currentItemCache = [];
57
58 this.resultsSize = {};
59
60 this.selected = null;
61
62 this.recentUploadsMessage = new OO.ui.LabelWidget( {
63 label: mw.msg( 'mw-widgets-mediasearch-recent-uploads', mw.user ),
64 classes: [ 'mw-widget-mediaSearchWidget-recentUploads' ]
65 } );
66 this.recentUploadsMessage.toggle( false );
67 this.noItemsMessage = new OO.ui.LabelWidget( {
68 label: mw.msg( 'mw-widgets-mediasearch-noresults' ),
69 classes: [ 'mw-widget-mediaSearchWidget-noResults' ]
70 } );
71 this.noItemsMessage.toggle( false );
72
73 // Events
74 this.$results.on( 'scroll', this.onResultsScroll.bind( this ) );
75 this.results.connect( this, {
76 change: 'onResultsChange',
77 remove: 'onResultsRemove'
78 } );
79
80 this.resizeHandler = OO.ui.debounce( this.afterResultsResize.bind( this ), 500 );
81
82 // Initialization
83 this.setLang( config.lang || 'en' );
84 this.$results.prepend( this.recentUploadsMessage.$element, this.noItemsMessage.$element );
85 this.$element.addClass( 'mw-widget-mediaSearchWidget' );
86
87 this.query.$input.attr( 'aria-label', mw.msg( 'mw-widgets-mediasearch-input-placeholder' ) );
88 this.results.$element.attr( 'aria-label', mw.msg( 'mw-widgets-mediasearch-results-aria-label' ) );
89 };
90
91 /* Inheritance */
92
93 OO.inheritClass( mw.widgets.MediaSearchWidget, OO.ui.SearchWidget );
94
95 /* Static properties */
96
97 mw.widgets.MediaSearchWidget.static.limit = 10;
98
99 mw.widgets.MediaSearchWidget.static.threshold = 5;
100
101 /* Methods */
102
103 /**
104 * Respond to window resize and check if the result display should
105 * be updated.
106 */
107 mw.widgets.MediaSearchWidget.prototype.afterResultsResize = function () {
108 const items = this.currentItemCache;
109
110 if (
111 items.length > 0 &&
112 (
113 this.resultsSize.width !== this.$results.width() ||
114 this.resultsSize.height !== this.$results.height()
115 )
116 ) {
117 this.resetRows();
118 this.itemCache = {};
119 this.processQueueResults( items );
120 if ( !this.results.isEmpty() ) {
121 this.lazyLoadResults();
122 }
123
124 // Cache the size
125 this.resultsSize = {
126 width: this.$results.width(),
127 height: this.$results.height()
128 };
129 }
130 };
131
132 /**
133 * Teardown the widget; disconnect the window resize event.
134 */
135 mw.widgets.MediaSearchWidget.prototype.teardown = function () {
136 $( window ).off( 'resize', this.resizeHandler );
137 };
138
139 /**
140 * Setup the widget; activate the resize event.
141 */
142 mw.widgets.MediaSearchWidget.prototype.setup = function () {
143 $( window ).on( 'resize', this.resizeHandler );
144 };
145
146 /**
147 * Query all sources for media.
148 *
149 * @method
150 */
151 mw.widgets.MediaSearchWidget.prototype.queryMediaQueue = function () {
152 const search = this,
153 value = this.getQueryValue();
154
155 if ( value === '' ) {
156 if ( mw.user.isAnon() ) {
157 return;
158 } else {
159 if ( this.currentQueue !== this.userUploadsQueue ) {
160 this.userUploadsQueue.reset();
161 }
162 this.currentQueue = this.userUploadsQueue;
163 // TODO: use cached results?
164 }
165 } else {
166 this.currentQueue = this.searchQueue;
167 this.currentQueue.setSearchQuery( value );
168 }
169
170 this.recentUploadsMessage.toggle( this.currentQueue === this.userUploadsQueue );
171
172 this.query.pushPending();
173 search.noItemsMessage.toggle( false );
174
175 this.currentQueue.get( this.constructor.static.limit )
176 .then( ( items ) => {
177 if ( items.length > 0 ) {
178 search.processQueueResults( items );
179 search.currentItemCache = search.currentItemCache.concat( items );
180 }
181
182 search.query.popPending();
183 search.noItemsMessage.toggle( search.results.isEmpty() );
184 if ( !search.results.isEmpty() ) {
185 search.lazyLoadResults();
186 }
187
188 } );
189 };
190
191 /**
192 * Process the media queue giving more items.
193 *
194 * @method
195 * @param {Object[]} items Given items by the media queue
196 */
197 mw.widgets.MediaSearchWidget.prototype.processQueueResults = function ( items ) {
198 const resultWidgets = [],
199 inputSearchQuery = this.getQueryValue(),
200 queueSearchQuery = this.searchQueue.getSearchQuery();
201
202 if (
203 this.currentQueue === this.searchQueue &&
204 ( inputSearchQuery === '' || queueSearchQuery !== inputSearchQuery )
205 ) {
206 return;
207 }
208
209 for ( let i = 0, len = items.length; i < len; i++ ) {
210 const title = new mw.Title( items[ i ].title ).getMainText();
211 // Do not insert duplicates
212 if ( !Object.prototype.hasOwnProperty.call( this.itemCache, title ) ) {
213 this.itemCache[ title ] = true;
214 resultWidgets.push(
215 new mw.widgets.MediaResultWidget( {
216 data: items[ i ],
217 rowHeight: this.rowHeight,
218 maxWidth: this.results.$element.width() / 3,
219 minWidth: 30,
220 rowWidth: this.results.$element.width()
221 } )
222 );
223 }
224 }
225 this.results.addItems( resultWidgets );
226
227 };
228
229 /**
230 * Get the sanitized query value from the input.
231 *
232 * @return {string} Query value
233 */
234 mw.widgets.MediaSearchWidget.prototype.getQueryValue = function () {
235 let queryValue = this.query.getValue().trim();
236
237 if ( queryValue.match( this.externalLinkUrlProtocolsRegExp ) ) {
238 queryValue = queryValue.match( /.+\/([^/]+)/ )[ 1 ];
239 }
240 return queryValue;
241 };
242
243 /**
244 * Handle search value change.
245 *
246 * @param {string} value New value
247 */
248 mw.widgets.MediaSearchWidget.prototype.onQueryChange = function () {
249 // Get the sanitized query value
250 const queryValue = this.getQueryValue();
251
252 if ( queryValue === this.lastQueryValue ) {
253 return;
254 }
255
256 // Parent method
257 mw.widgets.MediaSearchWidget.super.prototype.onQueryChange.apply( this, arguments );
258
259 // Reset
260 this.itemCache = {};
261 this.currentItemCache = [];
262 this.resetRows();
263 this.recentUploadsMessage.toggle( false );
264
265 // Empty the results queue
266 this.layoutQueue = [];
267
268 // Change resource queue query
269 this.searchQueue.setSearchQuery( queryValue );
270 this.lastQueryValue = queryValue;
271
272 // Queue
273 clearTimeout( this.queryTimeout );
274 this.queryTimeout = setTimeout( this.queryMediaQueue.bind( this ), 350 );
275 };
276
277 /**
278 * Handle results scroll events.
279 *
280 * @param {jQuery.Event} e Scroll event
281 */
282 mw.widgets.MediaSearchWidget.prototype.onResultsScroll = function () {
283 const position = this.$results.scrollTop() + this.$results.outerHeight(),
284 threshold = this.results.$element.outerHeight() - this.rowHeight * 3;
285
286 // Check if we need to ask for more results
287 if ( !this.query.isPending() && position > threshold ) {
288 this.queryMediaQueue();
289 }
290
291 this.lazyLoadResults();
292 };
293
294 /**
295 * Lazy-load the images that are visible.
296 */
297 mw.widgets.MediaSearchWidget.prototype.lazyLoadResults = function () {
298 const items = this.results.getItems(),
299 resultsScrollTop = this.$results.scrollTop(),
300 position = resultsScrollTop + this.$results.outerHeight();
301
302 // Lazy-load results
303 for ( let i = 0; i < items.length; i++ ) {
304 const elementTop = items[ i ].$element.position().top;
305 if ( elementTop <= position && !items[ i ].hasSrc() ) {
306 // Load the image
307 items[ i ].lazyLoad();
308 }
309 }
310 };
311
312 /**
313 * Reset all the rows; destroy the jQuery elements and reset
314 * the rows array.
315 */
316 mw.widgets.MediaSearchWidget.prototype.resetRows = function () {
317 for ( let i = 0, len = this.rows.length; i < len; i++ ) {
318 this.rows[ i ].$element.remove();
319 }
320
321 this.rows = [];
322 this.itemCache = {};
323 };
324
325 /**
326 * Find an available row at the end. Either we will need to create a new
327 * row or use the last available row if it isn't full.
328 *
329 * @return {number} Row index
330 */
331 mw.widgets.MediaSearchWidget.prototype.getAvailableRow = function () {
332 let row;
333
334 if ( this.rows.length === 0 ) {
335 row = 0;
336 } else {
337 row = this.rows.length - 1;
338 }
339
340 if ( !this.rows[ row ] ) {
341 // Create new row
342 this.rows[ row ] = {
343 isFull: false,
344 width: 0,
345 items: [],
346 $element: $( '<div>' )
347 .addClass( 'mw-widget-mediaResultWidget-row' )
348 .css( {
349 overflow: 'hidden'
350 } )
351 .data( 'row', row )
352 .attr( 'data-full', false )
353 };
354 // Append to results
355 this.results.$element.append( this.rows[ row ].$element );
356 } else if ( this.rows[ row ].isFull ) {
357 row++;
358 // Create new row
359 this.rows[ row ] = {
360 isFull: false,
361 width: 0,
362 items: [],
363 $element: $( '<div>' )
364 .addClass( 'mw-widget-mediaResultWidget-row' )
365 .css( {
366 overflow: 'hidden'
367 } )
368 .data( 'row', row )
369 .attr( 'data-full', false )
370 };
371 // Append to results
372 this.results.$element.append( this.rows[ row ].$element );
373 }
374
375 return row;
376 };
377
378 /**
379 * Respond to change results event in the results widget.
380 * Override the way SelectWidget and GroupElement append the items
381 * into the group so we can append them in groups of rows.
382 *
383 * @param {mw.widgets.MediaResultWidget[]} items An array of item elements
384 */
385 mw.widgets.MediaSearchWidget.prototype.onResultsChange = function ( items ) {
386 if ( !items.length ) {
387 return;
388 }
389
390 // Add method to a queue; this queue will only run when the widget
391 // is visible
392 this.layoutQueue.push( () => {
393 const maxRowWidth = this.results.$element.width() - 15;
394
395 // Go over the added items
396 let row = this.getAvailableRow();
397 for ( let i = 0, ilen = items.length; i < ilen; i++ ) {
398
399 // Check item has just been added
400 if ( items[ i ].row !== null ) {
401 continue;
402 }
403
404 const itemWidth = items[ i ].$element.outerWidth( true );
405
406 // Add items to row until it is full
407 if ( this.rows[ row ].width + itemWidth >= maxRowWidth ) {
408 // Mark this row as full
409 this.rows[ row ].isFull = true;
410 this.rows[ row ].$element.attr( 'data-full', true );
411
412 // Find the resize factor
413 const effectiveWidth = this.rows[ row ].width;
414 const resizeFactor = maxRowWidth / effectiveWidth;
415
416 this.rows[ row ].$element.attr( 'data-effectiveWidth', effectiveWidth );
417 this.rows[ row ].$element.attr( 'data-resizeFactor', resizeFactor );
418 this.rows[ row ].$element.attr( 'data-row', row );
419
420 // Resize all images in the row to fit the width
421 for ( let j = 0, jlen = this.rows[ row ].items.length; j < jlen; j++ ) {
422 this.rows[ row ].items[ j ].resizeThumb( resizeFactor );
423 }
424
425 // find another row
426 row = this.getAvailableRow();
427 }
428
429 // Add the cumulative
430 this.rows[ row ].width += itemWidth;
431
432 // Store reference to the item and to the row
433 this.rows[ row ].items.push( items[ i ] );
434 items[ i ].setRow( row );
435
436 // Append the item
437 this.rows[ row ].$element.append( items[ i ].$element );
438
439 }
440
441 // If we have less than 4 rows, call for more images
442 if ( this.rows.length < 4 ) {
443 this.queryMediaQueue();
444 }
445 } );
446 this.runLayoutQueue();
447 };
448
449 /**
450 * Run layout methods from the queue only if the element is visible.
451 */
452 mw.widgets.MediaSearchWidget.prototype.runLayoutQueue = function () {
453 // eslint-disable-next-line no-jquery/no-sizzle
454 if ( this.$element.is( ':visible' ) ) {
455 for ( let i = 0, len = this.layoutQueue.length; i < len; i++ ) {
456 this.layoutQueue.pop()();
457 }
458 }
459 };
460
461 /**
462 * Respond to removing results event in the results widget.
463 * Clear the relevant rows.
464 *
465 * @param {OO.ui.OptionWidget[]} items Removed items
466 */
467 mw.widgets.MediaSearchWidget.prototype.onResultsRemove = function ( items ) {
468 if ( items.length > 0 ) {
469 // In the case of the media search widget, if any items are removed
470 // all are removed (new search)
471 this.resetRows();
472 this.currentItemCache = [];
473 }
474 };
475
476 /**
477 * Set language for the search results.
478 *
479 * @param {string} lang Language
480 */
481 mw.widgets.MediaSearchWidget.prototype.setLang = function ( lang ) {
482 this.lang = lang;
483 this.searchQueue.setLang( lang );
484 };
485
486 /**
487 * Get language for the search results.
488 *
489 * @return {string} lang Language
490 */
491 mw.widgets.MediaSearchWidget.prototype.getLang = function () {
492 return this.lang;
493 };
494 }() );