Merge "mw.Upload.BookletLayout: Rewrite some code to use promise chaining"
[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 if ( this.shouldRecordBucket ) {
214 this.upload.bucket = this.bucket;
215 }
216
217 this.upload.setFile( file );
218 // The original file name might contain invalid characters, so use our sanitized one
219 this.upload.setFilename( this.getFilename() );
220
221 this.uploadPromise = this.upload.uploadToStash();
222 this.uploadPromise.then( function () {
223 deferred.resolve();
224 layout.emit( 'fileUploaded' );
225 }, function () {
226 // These errors will be thrown while the user is on the info page.
227 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
228 // really be an error...
229 var errorMessage = layout.getErrorMessageForStateDetails();
230 deferred.reject( errorMessage );
231 } );
232
233 // If there is an error in uploading, come back to the upload page
234 deferred.fail( function () {
235 layout.setPage( 'upload' );
236 } );
237
238 return deferred;
239 };
240
241 /**
242 * Saves the stash finalizes upload. Uses
243 * {@link #getFilename getFilename}, and
244 * {@link #getText getText} to get details from
245 * the form.
246 *
247 * @protected
248 * @fires fileSaved
249 * @return {jQuery.Promise} Rejects the promise with an
250 * {@link OO.ui.Error error}, or resolves if the upload was successful.
251 */
252 mw.Upload.BookletLayout.prototype.saveFile = function () {
253 var layout = this,
254 deferred = $.Deferred();
255
256 this.upload.setFilename( this.getFilename() );
257 this.upload.setText( this.getText() );
258
259 this.uploadPromise.then( function () {
260 layout.upload.finishStashUpload().then( function () {
261 var name;
262
263 // Normalize page name and localise the 'File:' prefix
264 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
265 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
266 layout.setPage( 'insert' );
267
268 deferred.resolve();
269 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
270 }, function () {
271 var errorMessage = layout.getErrorMessageForStateDetails();
272 deferred.reject( errorMessage );
273 } );
274 } );
275
276 return deferred.promise();
277 };
278
279 /**
280 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
281 * state and state details.
282 *
283 * @protected
284 * @return {OO.ui.Error} Error to display for given state and details.
285 */
286 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
287 var message,
288 state = this.upload.getState(),
289 stateDetails = this.upload.getStateDetails(),
290 error = stateDetails.error,
291 warnings = stateDetails.upload && stateDetails.upload.warnings;
292
293 if ( state === mw.Upload.State.ERROR ) {
294 if ( !error ) {
295 // If there's an 'exception' key, this might be a timeout, or other connection problem
296 return new OO.ui.Error(
297 $( '<p>' ).msg( 'api-error-unknownerror', JSON.stringify( stateDetails ) ),
298 { recoverable: false }
299 );
300 }
301
302 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
303 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
304 if ( error.info === 'TitleBlacklist prevents this title from being created' ) {
305 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
306 return new OO.ui.Error(
307 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
308 $( '<p>' ).msg( 'api-error-blacklisted' ),
309 { recoverable: false }
310 );
311 }
312
313 message = mw.message( 'api-error-' + error.code );
314 if ( !message.exists() ) {
315 message = mw.message( 'api-error-unknownerror', JSON.stringify( stateDetails ) );
316 }
317 return new OO.ui.Error(
318 $( '<p>' ).append( message.parseDom() ),
319 { recoverable: false }
320 );
321 }
322
323 if ( state === mw.Upload.State.WARNING ) {
324 // We could get more than one of these errors, these are in order
325 // of importance. For example fixing the thumbnail like file name
326 // won't help the fact that the file already exists.
327 if ( warnings.stashfailed !== undefined ) {
328 return new OO.ui.Error(
329 $( '<p>' ).msg( 'api-error-stashfailed' ),
330 { recoverable: false }
331 );
332 } else if ( warnings.exists !== undefined ) {
333 return new OO.ui.Error(
334 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
335 { recoverable: false }
336 );
337 } else if ( warnings[ 'page-exists' ] !== undefined ) {
338 return new OO.ui.Error(
339 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
340 { recoverable: false }
341 );
342 } else if ( warnings.duplicate !== undefined ) {
343 return new OO.ui.Error(
344 $( '<p>' ).msg( 'api-error-duplicate', warnings.duplicate.length ),
345 { recoverable: false }
346 );
347 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
348 return new OO.ui.Error(
349 $( '<p>' ).msg( 'filename-thumb-name' ),
350 { recoverable: false }
351 );
352 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
353 return new OO.ui.Error(
354 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
355 { recoverable: false }
356 );
357 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
358 return new OO.ui.Error(
359 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
360 { recoverable: false }
361 );
362 } else if ( warnings.badfilename !== undefined ) {
363 // Change the name if the current name isn't acceptable
364 // TODO This might not really be the best place to do this
365 this.setFilename( warnings.badfilename );
366 return new OO.ui.Error(
367 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
368 );
369 } else {
370 return new OO.ui.Error(
371 // Let's get all the help we can if we can't pin point the error
372 $( '<p>' ).msg( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ),
373 { recoverable: false }
374 );
375 }
376 }
377 };
378
379 /* Form renderers */
380
381 /**
382 * Renders and returns the upload form and sets the
383 * {@link #uploadForm uploadForm} property.
384 *
385 * @protected
386 * @fires selectFile
387 * @return {OO.ui.FormLayout}
388 */
389 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
390 var fieldset;
391
392 this.selectFileWidget = new OO.ui.SelectFileWidget();
393 fieldset = new OO.ui.FieldsetLayout( { label: mw.msg( 'upload-form-label-select-file' ) } );
394 fieldset.addItems( [ this.selectFileWidget ] );
395 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
396
397 // Validation
398 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
399
400 return this.uploadForm;
401 };
402
403 /**
404 * Handle change events to the upload form
405 *
406 * @protected
407 * @fires uploadValid
408 */
409 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
410 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
411 };
412
413 /**
414 * Renders and returns the information form for collecting
415 * metadata and sets the {@link #infoForm infoForm}
416 * property.
417 *
418 * @protected
419 * @return {OO.ui.FormLayout}
420 */
421 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
422 var fieldset;
423
424 this.filenameWidget = new OO.ui.TextInputWidget( {
425 indicator: 'required',
426 required: true,
427 validate: /.+/
428 } );
429 this.descriptionWidget = new OO.ui.TextInputWidget( {
430 indicator: 'required',
431 required: true,
432 validate: /\S+/,
433 multiline: true,
434 autosize: true
435 } );
436
437 fieldset = new OO.ui.FieldsetLayout( {
438 label: mw.msg( 'upload-form-label-infoform-title' )
439 } );
440 fieldset.addItems( [
441 new OO.ui.FieldLayout( this.filenameWidget, {
442 label: mw.msg( 'upload-form-label-infoform-name' ),
443 align: 'top',
444 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
445 } ),
446 new OO.ui.FieldLayout( this.descriptionWidget, {
447 label: mw.msg( 'upload-form-label-infoform-description' ),
448 align: 'top',
449 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
450 } )
451 ] );
452 this.infoForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
453
454 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
455 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
456
457 return this.infoForm;
458 };
459
460 /**
461 * Handle change events to the info form
462 *
463 * @protected
464 * @fires infoValid
465 */
466 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
467 var layout = this;
468 $.when(
469 this.filenameWidget.getValidity(),
470 this.descriptionWidget.getValidity()
471 ).done( function () {
472 layout.emit( 'infoValid', true );
473 } ).fail( function () {
474 layout.emit( 'infoValid', false );
475 } );
476 };
477
478 /**
479 * Renders and returns the insert form to show file usage and
480 * sets the {@link #insertForm insertForm} property.
481 *
482 * @protected
483 * @return {OO.ui.FormLayout}
484 */
485 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
486 var fieldset;
487
488 this.filenameUsageWidget = new OO.ui.TextInputWidget();
489 fieldset = new OO.ui.FieldsetLayout( {
490 label: mw.msg( 'upload-form-label-usage-title' )
491 } );
492 fieldset.addItems( [
493 new OO.ui.FieldLayout( this.filenameUsageWidget, {
494 label: mw.msg( 'upload-form-label-usage-filename' ),
495 align: 'top'
496 } )
497 ] );
498 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
499
500 return this.insertForm;
501 };
502
503 /* Getters */
504
505 /**
506 * Gets the file object from the
507 * {@link #uploadForm upload form}.
508 *
509 * @protected
510 * @return {File|null}
511 */
512 mw.Upload.BookletLayout.prototype.getFile = function () {
513 return this.selectFileWidget.getValue();
514 };
515
516 /**
517 * Gets the file name from the
518 * {@link #infoForm information form}.
519 *
520 * @protected
521 * @return {string}
522 */
523 mw.Upload.BookletLayout.prototype.getFilename = function () {
524 var filename = this.filenameWidget.getValue();
525 if ( this.filenameExtension ) {
526 filename += '.' + this.filenameExtension;
527 }
528 return filename;
529 };
530
531 /**
532 * Prefills the {@link #infoForm information form} with the given filename.
533 *
534 * @protected
535 * @param {string} filename
536 */
537 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
538 var title = mw.Title.newFromFileName( filename );
539
540 if ( title ) {
541 this.filenameWidget.setValue( title.getNameText() );
542 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
543 } else {
544 // Seems to happen for files with no extension, which should fail some checks anyway...
545 this.filenameWidget.setValue( filename );
546 this.filenameExtension = null;
547 }
548 };
549
550 /**
551 * Gets the page text from the
552 * {@link #infoForm information form}.
553 *
554 * @protected
555 * @return {string}
556 */
557 mw.Upload.BookletLayout.prototype.getText = function () {
558 return this.descriptionWidget.getValue();
559 };
560
561 /* Setters */
562
563 /**
564 * Sets the file object
565 *
566 * @protected
567 * @param {File|null} file File to select
568 */
569 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
570 this.selectFileWidget.setValue( file );
571 };
572
573 /**
574 * Clear the values of all fields
575 *
576 * @protected
577 */
578 mw.Upload.BookletLayout.prototype.clear = function () {
579 this.selectFileWidget.setValue( null );
580 this.filenameWidget.setValue( null ).setValidityFlag( true );
581 this.descriptionWidget.setValue( null ).setValidityFlag( true );
582 this.filenameUsageWidget.setValue( null );
583 };
584
585 }( jQuery, mediaWiki ) );