Merge "Add additional tracking information to mediawiki.searchSuggest"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.Upload.BookletLayout.js
1 /*global moment*/
2 ( function ( $, mw, moment ) {
3
4 /**
5 * mw.Upload.BookletLayout encapsulates the process of uploading a file
6 * to MediaWiki using the {@link mw.Upload upload model}.
7 * The booklet emits events that can be used to get the stashed
8 * upload and the final file. It can be extended to accept
9 * additional fields from the user for specific scenarios like
10 * for Commons, or campaigns.
11 *
12 * ## Structure
13 *
14 * The {@link OO.ui.BookletLayout booklet layout} has three steps:
15 *
16 * - **Upload**: Has a {@link OO.ui.SelectFileWidget field} to get the file object.
17 *
18 * - **Information**: Has a {@link OO.ui.FormLayout form} to collect metadata. This can be
19 * extended.
20 *
21 * - **Insert**: Has details on how to use the file that was uploaded.
22 *
23 * Each step has a form associated with it defined in
24 * {@link #renderUploadForm renderUploadForm},
25 * {@link #renderInfoForm renderInfoForm}, and
26 * {@link #renderInsertForm renderInfoForm}. The
27 * {@link #getFile getFile},
28 * {@link #getFilename getFilename}, and
29 * {@link #getText getText} methods are used to get
30 * the information filled in these forms, required to call
31 * {@link mw.Upload mw.Upload}.
32 *
33 * ## Usage
34 *
35 * See the {@link mw.Upload.Dialog upload dialog}.
36 *
37 * The {@link #event-fileUploaded fileUploaded},
38 * and {@link #event-fileSaved fileSaved} events can
39 * be used to get details of the upload.
40 *
41 * ## Extending
42 *
43 * To extend using {@link mw.Upload mw.Upload}, override
44 * {@link #renderInfoForm renderInfoForm} to render
45 * the form required for the specific use-case. Update the
46 * {@link #getFilename getFilename}, and
47 * {@link #getText getText} methods to return data
48 * from your newly created form. If you added new fields you'll also have
49 * to update the {@link #clear} method.
50 *
51 * If you plan to use a different upload model, apart from what is mentioned
52 * above, you'll also have to override the
53 * {@link #createUpload createUpload} method to
54 * return the new model. The {@link #saveFile saveFile}, and
55 * the {@link #uploadFile uploadFile} methods need to be
56 * overridden to use the new model and data returned from the forms.
57 *
58 * @class
59 * @extends OO.ui.BookletLayout
60 *
61 * @constructor
62 * @param {Object} config Configuration options
63 * @cfg {jQuery} [$overlay] Overlay to use for widgets in the booklet
64 */
65 mw.Upload.BookletLayout = function ( config ) {
66 // Parent constructor
67 mw.Upload.BookletLayout.parent.call( this, config );
68
69 this.$overlay = config.$overlay;
70
71 this.renderUploadForm();
72 this.renderInfoForm();
73 this.renderInsertForm();
74
75 this.addPages( [
76 new OO.ui.PageLayout( 'upload', {
77 scrollable: true,
78 padded: true,
79 content: [ this.uploadForm ]
80 } ),
81 new OO.ui.PageLayout( 'info', {
82 scrollable: true,
83 padded: true,
84 content: [ this.infoForm ]
85 } ),
86 new OO.ui.PageLayout( 'insert', {
87 scrollable: true,
88 padded: true,
89 content: [ this.insertForm ]
90 } )
91 ] );
92 };
93
94 /* Setup */
95
96 OO.inheritClass( mw.Upload.BookletLayout, OO.ui.BookletLayout );
97
98 /* Events */
99
100 /**
101 * Progress events for the uploaded file
102 *
103 * @event fileUploadProgress
104 * @param {number} progress In percentage
105 * @param {Object} duration Duration object from `moment.duration()`
106 */
107
108 /**
109 * The file has finished uploading
110 *
111 * @event fileUploaded
112 */
113
114 /**
115 * The file has been saved to the database
116 *
117 * @event fileSaved
118 * @param {Object} imageInfo See mw.Upload#getImageInfo
119 */
120
121 /**
122 * The upload form has changed
123 *
124 * @event uploadValid
125 * @param {boolean} isValid The form is valid
126 */
127
128 /**
129 * The info form has changed
130 *
131 * @event infoValid
132 * @param {boolean} isValid The form is valid
133 */
134
135 /* Properties */
136
137 /**
138 * @property {OO.ui.FormLayout} uploadForm
139 * The form rendered in the first step to get the file object.
140 * Rendered in {@link #renderUploadForm renderUploadForm}.
141 */
142
143 /**
144 * @property {OO.ui.FormLayout} infoForm
145 * The form rendered in the second step to get metadata.
146 * Rendered in {@link #renderInfoForm renderInfoForm}
147 */
148
149 /**
150 * @property {OO.ui.FormLayout} insertForm
151 * The form rendered in the third step to show usage
152 * Rendered in {@link #renderInsertForm renderInsertForm}
153 */
154
155 /* Methods */
156
157 /**
158 * Initialize for a new upload
159 *
160 * @return {jQuery.Promise} Promise resolved when everything is initialized
161 */
162 mw.Upload.BookletLayout.prototype.initialize = function () {
163 var booklet = this;
164
165 this.clear();
166 this.upload = this.createUpload();
167 this.setPage( 'upload' );
168
169 return this.upload.getApi().then(
170 function ( api ) {
171 // If the user can't upload anything, don't give them the option to.
172 return api.getUserInfo().then(
173 function ( userInfo ) {
174 if ( userInfo.rights.indexOf( 'upload' ) === -1 ) {
175 // TODO Use a better error message when not all logged-in users can upload
176 booklet.getPage( 'upload' ).$element.msg( 'api-error-mustbeloggedin' );
177 }
178 return $.Deferred().resolve();
179 },
180 function () {
181 return $.Deferred().resolve();
182 }
183 );
184 },
185 function ( errorMsg ) {
186 booklet.getPage( 'upload' ).$element.msg( errorMsg );
187 return $.Deferred().resolve();
188 }
189 );
190 };
191
192 /**
193 * Create a new upload model
194 *
195 * @protected
196 * @return {mw.Upload} Upload model
197 */
198 mw.Upload.BookletLayout.prototype.createUpload = function () {
199 return new mw.Upload();
200 };
201
202 /* Uploading */
203
204 /**
205 * Uploads the file that was added in the upload form. Uses
206 * {@link #getFile getFile} to get the HTML5
207 * file object.
208 *
209 * @protected
210 * @fires fileUploadProgress
211 * @fires fileUploaded
212 * @return {jQuery.Promise}
213 */
214 mw.Upload.BookletLayout.prototype.uploadFile = function () {
215 var deferred = $.Deferred(),
216 startTime = new Date(),
217 layout = this,
218 file = this.getFile();
219
220 this.setFilename( file.name );
221
222 this.setPage( 'info' );
223
224 this.upload.setFile( file );
225 // The original file name might contain invalid characters, so use our sanitized one
226 this.upload.setFilename( this.getFilename() );
227
228 this.uploadPromise = this.upload.uploadToStash();
229 this.uploadPromise.then( function () {
230 deferred.resolve();
231 layout.emit( 'fileUploaded' );
232 }, function () {
233 // These errors will be thrown while the user is on the info page.
234 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
235 // really be an error...
236 var errorMessage = layout.getErrorMessageForStateDetails();
237 deferred.reject( errorMessage );
238 }, function ( progress ) {
239 var elapsedTime = new Date() - startTime,
240 estimatedTotalTime = ( 1 / progress ) * elapsedTime,
241 estimatedRemainingTime = moment.duration( estimatedTotalTime - elapsedTime );
242 layout.emit( 'fileUploadProgress', progress, estimatedRemainingTime );
243 } );
244
245 // If there is an error in uploading, come back to the upload page
246 deferred.fail( function () {
247 layout.setPage( 'upload' );
248 } );
249
250 return deferred;
251 };
252
253 /**
254 * Saves the stash finalizes upload. Uses
255 * {@link #getFilename getFilename}, and
256 * {@link #getText getText} to get details from
257 * the form.
258 *
259 * @protected
260 * @fires fileSaved
261 * @return {jQuery.Promise} Rejects the promise with an
262 * {@link OO.ui.Error error}, or resolves if the upload was successful.
263 */
264 mw.Upload.BookletLayout.prototype.saveFile = function () {
265 var layout = this,
266 deferred = $.Deferred();
267
268 this.upload.setFilename( this.getFilename() );
269 this.upload.setText( this.getText() );
270
271 this.uploadPromise.then( function () {
272 layout.upload.finishStashUpload().then( function () {
273 var name;
274
275 // Normalize page name and localise the 'File:' prefix
276 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
277 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
278 layout.setPage( 'insert' );
279
280 deferred.resolve();
281 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
282 }, function () {
283 var errorMessage = layout.getErrorMessageForStateDetails();
284 deferred.reject( errorMessage );
285 } );
286 } );
287
288 return deferred.promise();
289 };
290
291 /**
292 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
293 * state and state details.
294 *
295 * @protected
296 * @return {OO.ui.Error} Error to display for given state and details.
297 */
298 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
299 var message,
300 state = this.upload.getState(),
301 stateDetails = this.upload.getStateDetails(),
302 error = stateDetails.error,
303 warnings = stateDetails.upload && stateDetails.upload.warnings;
304
305 if ( state === mw.Upload.State.ERROR ) {
306 if ( !error ) {
307 // If there's an 'exception' key, this might be a timeout, or other connection problem
308 return new OO.ui.Error(
309 $( '<p>' ).msg( 'api-error-unknownerror', JSON.stringify( stateDetails ) ),
310 { recoverable: false }
311 );
312 }
313
314 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
315 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
316 if ( error.info === 'TitleBlacklist prevents this title from being created' ) {
317 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
318 return new OO.ui.Error(
319 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
320 $( '<p>' ).msg( 'api-error-blacklisted' ),
321 { recoverable: false }
322 );
323 }
324
325 message = mw.message( 'api-error-' + error.code );
326 if ( !message.exists() ) {
327 message = mw.message( 'api-error-unknownerror', JSON.stringify( stateDetails ) );
328 }
329 return new OO.ui.Error(
330 $( '<p>' ).append( message.parseDom() ),
331 { recoverable: false }
332 );
333 }
334
335 if ( state === mw.Upload.State.WARNING ) {
336 // We could get more than one of these errors, these are in order
337 // of importance. For example fixing the thumbnail like file name
338 // won't help the fact that the file already exists.
339 if ( warnings.stashfailed !== undefined ) {
340 return new OO.ui.Error(
341 $( '<p>' ).msg( 'api-error-stashfailed' ),
342 { recoverable: false }
343 );
344 } else if ( warnings.exists !== undefined ) {
345 return new OO.ui.Error(
346 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
347 { recoverable: false }
348 );
349 } else if ( warnings[ 'page-exists' ] !== undefined ) {
350 return new OO.ui.Error(
351 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
352 { recoverable: false }
353 );
354 } else if ( warnings.duplicate !== undefined ) {
355 return new OO.ui.Error(
356 $( '<p>' ).msg( 'api-error-duplicate', warnings.duplicate.length ),
357 { recoverable: false }
358 );
359 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
360 return new OO.ui.Error(
361 $( '<p>' ).msg( 'filename-thumb-name' ),
362 { recoverable: false }
363 );
364 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
365 return new OO.ui.Error(
366 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
367 { recoverable: false }
368 );
369 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
370 return new OO.ui.Error(
371 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
372 { recoverable: false }
373 );
374 } else if ( warnings.badfilename !== undefined ) {
375 // Change the name if the current name isn't acceptable
376 // TODO This might not really be the best place to do this
377 this.setFilename( warnings.badfilename );
378 return new OO.ui.Error(
379 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
380 );
381 } else {
382 return new OO.ui.Error(
383 // Let's get all the help we can if we can't pin point the error
384 $( '<p>' ).msg( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ),
385 { recoverable: false }
386 );
387 }
388 }
389 };
390
391 /* Form renderers */
392
393 /**
394 * Renders and returns the upload form and sets the
395 * {@link #uploadForm uploadForm} property.
396 *
397 * @protected
398 * @fires selectFile
399 * @return {OO.ui.FormLayout}
400 */
401 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
402 var fieldset,
403 layout = this;
404
405 this.selectFileWidget = new OO.ui.SelectFileWidget( {
406 showDropTarget: true
407 } );
408 fieldset = new OO.ui.FieldsetLayout();
409 fieldset.addItems( [ this.selectFileWidget ] );
410 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
411
412 // Validation
413 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
414
415 this.selectFileWidget.on( 'change', function () {
416 layout.updateFilePreview();
417 } );
418
419 return this.uploadForm;
420 };
421
422 /**
423 * Updates the file preview on the info form when a file is added.
424 *
425 * @protected
426 */
427 mw.Upload.BookletLayout.prototype.updateFilePreview = function () {
428 this.selectFileWidget.loadAndGetImageUrl().done( function ( url ) {
429 this.filePreview.$element.find( 'p' ).remove();
430 this.filePreview.$element.css( 'background-image', 'url(' + url + ')' );
431 this.infoForm.$element.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
432 }.bind( this ) ).fail( function () {
433 this.filePreview.$element.find( 'p' ).remove();
434 if ( this.selectFileWidget.getValue() ) {
435 this.filePreview.$element.append(
436 $( '<p>' ).text( this.selectFileWidget.getValue().name )
437 );
438 }
439 this.filePreview.$element.css( 'background-image', '' );
440 this.infoForm.$element.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
441 }.bind( this ) );
442 };
443
444 /**
445 * Handle change events to the upload form
446 *
447 * @protected
448 * @fires uploadValid
449 */
450 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
451 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
452 };
453
454 /**
455 * Renders and returns the information form for collecting
456 * metadata and sets the {@link #infoForm infoForm}
457 * property.
458 *
459 * @protected
460 * @return {OO.ui.FormLayout}
461 */
462 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
463 var fieldset;
464
465 this.filePreview = new OO.ui.Widget( {
466 classes: [ 'mw-upload-bookletLayout-filePreview' ]
467 } );
468 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
469 progress: 0
470 } );
471 this.filePreview.$element.append( this.progressBarWidget.$element );
472
473 this.filenameWidget = new OO.ui.TextInputWidget( {
474 indicator: 'required',
475 required: true,
476 validate: /.+/
477 } );
478 this.descriptionWidget = new OO.ui.TextInputWidget( {
479 indicator: 'required',
480 required: true,
481 validate: /\S+/,
482 multiline: true,
483 autosize: true
484 } );
485
486 fieldset = new OO.ui.FieldsetLayout( {
487 label: mw.msg( 'upload-form-label-infoform-title' )
488 } );
489 fieldset.addItems( [
490 new OO.ui.FieldLayout( this.filenameWidget, {
491 label: mw.msg( 'upload-form-label-infoform-name' ),
492 align: 'top',
493 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
494 } ),
495 new OO.ui.FieldLayout( this.descriptionWidget, {
496 label: mw.msg( 'upload-form-label-infoform-description' ),
497 align: 'top',
498 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
499 } )
500 ] );
501 this.infoForm = new OO.ui.FormLayout( {
502 classes: [ 'mw-upload-bookletLayout-infoForm' ],
503 items: [ this.filePreview, fieldset ]
504 } );
505
506 this.on( 'fileUploadProgress', function ( progress ) {
507 this.progressBarWidget.setProgress( progress * 100 );
508 }.bind( this ) );
509
510 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
511 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
512
513 return this.infoForm;
514 };
515
516 /**
517 * Handle change events to the info form
518 *
519 * @protected
520 * @fires infoValid
521 */
522 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
523 var layout = this;
524 $.when(
525 this.filenameWidget.getValidity(),
526 this.descriptionWidget.getValidity()
527 ).done( function () {
528 layout.emit( 'infoValid', true );
529 } ).fail( function () {
530 layout.emit( 'infoValid', false );
531 } );
532 };
533
534 /**
535 * Renders and returns the insert form to show file usage and
536 * sets the {@link #insertForm insertForm} property.
537 *
538 * @protected
539 * @return {OO.ui.FormLayout}
540 */
541 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
542 var fieldset;
543
544 this.filenameUsageWidget = new OO.ui.TextInputWidget();
545 fieldset = new OO.ui.FieldsetLayout( {
546 label: mw.msg( 'upload-form-label-usage-title' )
547 } );
548 fieldset.addItems( [
549 new OO.ui.FieldLayout( this.filenameUsageWidget, {
550 label: mw.msg( 'upload-form-label-usage-filename' ),
551 align: 'top'
552 } )
553 ] );
554 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
555
556 return this.insertForm;
557 };
558
559 /* Getters */
560
561 /**
562 * Gets the file object from the
563 * {@link #uploadForm upload form}.
564 *
565 * @protected
566 * @return {File|null}
567 */
568 mw.Upload.BookletLayout.prototype.getFile = function () {
569 return this.selectFileWidget.getValue();
570 };
571
572 /**
573 * Gets the file name from the
574 * {@link #infoForm information form}.
575 *
576 * @protected
577 * @return {string}
578 */
579 mw.Upload.BookletLayout.prototype.getFilename = function () {
580 var filename = this.filenameWidget.getValue();
581 if ( this.filenameExtension ) {
582 filename += '.' + this.filenameExtension;
583 }
584 return filename;
585 };
586
587 /**
588 * Prefills the {@link #infoForm information form} with the given filename.
589 *
590 * @protected
591 * @param {string} filename
592 */
593 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
594 var title = mw.Title.newFromFileName( filename );
595
596 if ( title ) {
597 this.filenameWidget.setValue( title.getNameText() );
598 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
599 } else {
600 // Seems to happen for files with no extension, which should fail some checks anyway...
601 this.filenameWidget.setValue( filename );
602 this.filenameExtension = null;
603 }
604 };
605
606 /**
607 * Gets the page text from the
608 * {@link #infoForm information form}.
609 *
610 * @protected
611 * @return {string}
612 */
613 mw.Upload.BookletLayout.prototype.getText = function () {
614 return this.descriptionWidget.getValue();
615 };
616
617 /* Setters */
618
619 /**
620 * Sets the file object
621 *
622 * @protected
623 * @param {File|null} file File to select
624 */
625 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
626 this.selectFileWidget.setValue( file );
627 };
628
629 /**
630 * Clear the values of all fields
631 *
632 * @protected
633 */
634 mw.Upload.BookletLayout.prototype.clear = function () {
635 this.selectFileWidget.setValue( null );
636 this.progressBarWidget.setProgress( 0 );
637 this.filenameWidget.setValue( null ).setValidityFlag( true );
638 this.descriptionWidget.setValue( null ).setValidityFlag( true );
639 this.filenameUsageWidget.setValue( null );
640 };
641
642 }( jQuery, mediaWiki, moment ) );