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