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