mw.Upload: Refactor error handling for the umpteenth time
[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 * overriden 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 */
110
111 /**
112 * The upload form has changed
113 *
114 * @event uploadValid
115 * @param {boolean} isValid The form is valid
116 */
117
118 /**
119 * The info form has changed
120 *
121 * @event infoValid
122 * @param {boolean} isValid The form is valid
123 */
124
125 /* Properties */
126
127 /**
128 * @property {OO.ui.FormLayout} uploadForm
129 * The form rendered in the first step to get the file object.
130 * Rendered in {@link #renderUploadForm renderUploadForm}.
131 */
132
133 /**
134 * @property {OO.ui.FormLayout} infoForm
135 * The form rendered in the second step to get metadata.
136 * Rendered in {@link #renderInfoForm renderInfoForm}
137 */
138
139 /**
140 * @property {OO.ui.FormLayout} insertForm
141 * The form rendered in the third step to show usage
142 * Rendered in {@link #renderInsertForm renderInsertForm}
143 */
144
145 /* Methods */
146
147 /**
148 * Initialize for a new upload
149 */
150 mw.Upload.BookletLayout.prototype.initialize = function () {
151 this.clear();
152 this.upload = this.createUpload();
153 this.setPage( 'upload' );
154 };
155
156 /**
157 * Create a new upload model
158 *
159 * @protected
160 * @return {mw.Upload} Upload model
161 */
162 mw.Upload.BookletLayout.prototype.createUpload = function () {
163 return new mw.Upload();
164 };
165
166 /* Uploading */
167
168 /**
169 * Uploads the file that was added in the upload form. Uses
170 * {@link #getFile getFile} to get the HTML5
171 * file object.
172 *
173 * @protected
174 * @fires fileUploaded
175 * @return {jQuery.Promise}
176 */
177 mw.Upload.BookletLayout.prototype.uploadFile = function () {
178 var deferred = $.Deferred(),
179 layout = this,
180 file = this.getFile();
181
182 this.filenameWidget.setValue( file.name );
183 this.setPage( 'info' );
184
185 this.upload.setFile( file );
186 // Explicitly set the filename so that the old filename isn't used in case of retry
187 this.upload.setFilenameFromFile();
188
189 this.uploadPromise = this.upload.uploadToStash();
190 this.uploadPromise.then( function () {
191 deferred.resolve();
192 layout.emit( 'fileUploaded' );
193 }, function () {
194 // These errors will be thrown while the user is on the info page.
195 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
196 // really be an error...
197 var errorMessage = layout.getErrorMessageForStateDetails();
198 deferred.reject( errorMessage );
199 } );
200
201 // If there is an error in uploading, come back to the upload page
202 deferred.fail( function () {
203 layout.setPage( 'upload' );
204 } );
205
206 return deferred;
207 };
208
209 /**
210 * Saves the stash finalizes upload. Uses
211 * {@link #getFilename getFilename}, and
212 * {@link #getText getText} to get details from
213 * the form.
214 *
215 * @protected
216 * @fires fileSaved
217 * @returns {jQuery.Promise} Rejects the promise with an
218 * {@link OO.ui.Error error}, or resolves if the upload was successful.
219 */
220 mw.Upload.BookletLayout.prototype.saveFile = function () {
221 var layout = this,
222 deferred = $.Deferred();
223
224 this.upload.setFilename( this.getFilename() );
225 this.upload.setText( this.getText() );
226
227 this.uploadPromise.then( function () {
228 layout.upload.finishStashUpload().then( function () {
229 var name;
230
231 // Normalize page name and localise the 'File:' prefix
232 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
233 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
234 layout.setPage( 'insert' );
235
236 deferred.resolve();
237 layout.emit( 'fileSaved' );
238 }, function () {
239 var errorMessage = layout.getErrorMessageForStateDetails();
240 deferred.reject( errorMessage );
241 } );
242 } );
243
244 return deferred.promise();
245 };
246
247 /**
248 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
249 * state and state details.
250 *
251 * @protected
252 * @returns {OO.ui.Error} Error to display for given state and details.
253 */
254 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
255 var message,
256 state = this.upload.getState(),
257 stateDetails = this.upload.getStateDetails(),
258 error = stateDetails.error,
259 warnings = stateDetails.upload && stateDetails.upload.warnings;
260
261 if ( state === mw.Upload.State.ERROR ) {
262 message = mw.message( 'api-error-' + error.code );
263 if ( !message.exists() ) {
264 message = mw.message( 'api-error-unknownerror', JSON.stringify( stateDetails ) );
265 }
266 return new OO.ui.Error(
267 $( '<p>' ).html(
268 message.parse()
269 ),
270 { recoverable: false }
271 );
272 }
273
274 if ( state === mw.Upload.State.WARNING ) {
275 // We could get more than one of these errors, these are in order
276 // of importance. For example fixing the thumbnail like file name
277 // won't help the fact that the file already exists.
278 if ( warnings.stashfailed !== undefined ) {
279 return new OO.ui.Error(
280 $( '<p>' ).html(
281 mw.message( 'api-error-stashfailed' ).parse()
282 ),
283 { recoverable: false }
284 );
285 } else if ( warnings.exists !== undefined ) {
286 return new OO.ui.Error(
287 $( '<p>' ).html(
288 mw.message( 'filepageexists', warnings.exists ).parse()
289 ),
290 { recoverable: false }
291 );
292 } else if ( warnings.duplicate !== undefined ) {
293 return new OO.ui.Error(
294 $( '<p>' ).html(
295 mw.message( 'fileexists', warnings.duplicate[ 0 ] ).parse()
296 ),
297 { recoverable: false }
298 );
299 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
300 return new OO.ui.Error(
301 $( '<p>' ).html(
302 mw.message( 'filename-thumb-name' ).parse()
303 ),
304 { recoverable: false }
305 );
306 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
307 return new OO.ui.Error(
308 $( '<p>' ).html(
309 mw.message( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ).parse()
310 ),
311 { recoverable: false }
312 );
313 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
314 return new OO.ui.Error(
315 $( '<p>' ).html(
316 mw.message( 'api-error-duplicate-archive', warnings[ 'duplicate-archive' ] ).parse()
317 ),
318 { recoverable: false }
319 );
320 } else if ( warnings.badfilename !== undefined ) {
321 // Change the name if the current name isn't acceptable
322 // TODO This might not really be the best place to do this
323 this.filenameWidget.setValue( warnings.badfilename );
324 return new OO.ui.Error(
325 $( '<p>' ).html(
326 mw.message( 'badfilename', warnings.badfilename ).parse()
327 )
328 );
329 } else {
330 return new OO.ui.Error(
331 $( '<p>' ).html(
332 // Let's get all the help we can if we can't pin point the error
333 mw.message( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ).parse()
334 ),
335 { recoverable: false }
336 );
337 }
338 }
339 };
340
341 /* Form renderers */
342
343 /**
344 * Renders and returns the upload form and sets the
345 * {@link #uploadForm uploadForm} property.
346 *
347 * @protected
348 * @fires selectFile
349 * @returns {OO.ui.FormLayout}
350 */
351 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
352 var fieldset;
353
354 this.selectFileWidget = new OO.ui.SelectFileWidget();
355 fieldset = new OO.ui.FieldsetLayout( { label: mw.msg( 'upload-form-label-select-file' ) } );
356 fieldset.addItems( [ this.selectFileWidget ] );
357 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
358
359 // Validation
360 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
361
362 return this.uploadForm;
363 };
364
365 /**
366 * Handle change events to the upload form
367 *
368 * @protected
369 * @fires uploadValid
370 */
371 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
372 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
373 };
374
375 /**
376 * Renders and returns the information form for collecting
377 * metadata and sets the {@link #infoForm infoForm}
378 * property.
379 *
380 * @protected
381 * @returns {OO.ui.FormLayout}
382 */
383 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
384 var fieldset;
385
386 this.filenameWidget = new OO.ui.TextInputWidget( {
387 indicator: 'required',
388 required: true,
389 validate: /.+/
390 } );
391 this.descriptionWidget = new OO.ui.TextInputWidget( {
392 indicator: 'required',
393 required: true,
394 validate: /.+/,
395 multiline: true,
396 autosize: true
397 } );
398
399 fieldset = new OO.ui.FieldsetLayout( {
400 label: mw.msg( 'upload-form-label-infoform-title' )
401 } );
402 fieldset.addItems( [
403 new OO.ui.FieldLayout( this.filenameWidget, {
404 label: mw.msg( 'upload-form-label-infoform-name' ),
405 align: 'top'
406 } ),
407 new OO.ui.FieldLayout( this.descriptionWidget, {
408 label: mw.msg( 'upload-form-label-infoform-description' ),
409 align: 'top'
410 } )
411 ] );
412 this.infoForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
413
414 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
415 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
416
417 return this.infoForm;
418 };
419
420 /**
421 * Handle change events to the info form
422 *
423 * @protected
424 * @fires infoValid
425 */
426 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
427 var layout = this;
428 $.when(
429 this.filenameWidget.getValidity(),
430 this.descriptionWidget.getValidity()
431 ).done( function () {
432 layout.emit( 'infoValid', true );
433 } ).fail( function () {
434 layout.emit( 'infoValid', false );
435 } );
436 };
437
438 /**
439 * Renders and returns the insert form to show file usage and
440 * sets the {@link #insertForm insertForm} property.
441 *
442 * @protected
443 * @returns {OO.ui.FormLayout}
444 */
445 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
446 var fieldset;
447
448 this.filenameUsageWidget = new OO.ui.TextInputWidget();
449 fieldset = new OO.ui.FieldsetLayout( {
450 label: mw.msg( 'upload-form-label-usage-title' )
451 } );
452 fieldset.addItems( [
453 new OO.ui.FieldLayout( this.filenameUsageWidget, {
454 label: mw.msg( 'upload-form-label-usage-filename' ),
455 align: 'top'
456 } )
457 ] );
458 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
459
460 return this.insertForm;
461 };
462
463 /* Getters */
464
465 /**
466 * Gets the file object from the
467 * {@link #uploadForm upload form}.
468 *
469 * @protected
470 * @returns {File|null}
471 */
472 mw.Upload.BookletLayout.prototype.getFile = function () {
473 return this.selectFileWidget.getValue();
474 };
475
476 /**
477 * Gets the file name from the
478 * {@link #infoForm information form}.
479 *
480 * @protected
481 * @returns {string}
482 */
483 mw.Upload.BookletLayout.prototype.getFilename = function () {
484 return this.filenameWidget.getValue();
485 };
486
487 /**
488 * Gets the page text from the
489 * {@link #infoForm information form}.
490 *
491 * @protected
492 * @returns {string}
493 */
494 mw.Upload.BookletLayout.prototype.getText = function () {
495 return this.descriptionWidget.getValue();
496 };
497
498 /* Setters */
499
500 /**
501 * Sets the file object
502 *
503 * @protected
504 * @param {File|null} file File to select
505 */
506 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
507 this.selectFileWidget.setValue( file );
508 };
509
510 /**
511 * Clear the values of all fields
512 *
513 * @protected
514 */
515 mw.Upload.BookletLayout.prototype.clear = function () {
516 this.selectFileWidget.setValue( null );
517 this.filenameWidget.setValue( null ).setValidityFlag( true );
518 this.descriptionWidget.setValue( null ).setValidityFlag( true );
519 this.filenameUsageWidget.setValue( null );
520 };
521
522 }( jQuery, mediaWiki ) );