Merge "jquery.accessKeyLabel: make modifier info public"
[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
155 booklet = this,
156 deferred = $.Deferred();
157
158 this.clear();
159 this.upload = this.createUpload();
160 this.setPage( 'upload' );
161
162 this.upload.getApi().done( function ( api ) {
163 // If the user can't upload anything, don't give them the option to.
164 api.getUserInfo().done( 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 } ).always( function () {
170 deferred.resolve();
171 } );
172 } );
173
174 return deferred.promise();
175 };
176
177 /**
178 * Create a new upload model
179 *
180 * @protected
181 * @return {mw.Upload} Upload model
182 */
183 mw.Upload.BookletLayout.prototype.createUpload = function () {
184 return new mw.Upload();
185 };
186
187 /* Uploading */
188
189 /**
190 * Uploads the file that was added in the upload form. Uses
191 * {@link #getFile getFile} to get the HTML5
192 * file object.
193 *
194 * @protected
195 * @fires fileUploaded
196 * @return {jQuery.Promise}
197 */
198 mw.Upload.BookletLayout.prototype.uploadFile = function () {
199 var deferred = $.Deferred(),
200 layout = this,
201 file = this.getFile();
202
203 this.setFilename( file.name );
204
205 this.setPage( 'info' );
206
207 if ( this.shouldRecordBucket ) {
208 this.upload.bucket = this.bucket;
209 }
210
211 this.upload.setFile( file );
212 // The original file name might contain invalid characters, so use our sanitized one
213 this.upload.setFilename( this.getFilename() );
214
215 this.uploadPromise = this.upload.uploadToStash();
216 this.uploadPromise.then( function () {
217 deferred.resolve();
218 layout.emit( 'fileUploaded' );
219 }, function () {
220 // These errors will be thrown while the user is on the info page.
221 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
222 // really be an error...
223 var errorMessage = layout.getErrorMessageForStateDetails();
224 deferred.reject( errorMessage );
225 } );
226
227 // If there is an error in uploading, come back to the upload page
228 deferred.fail( function () {
229 layout.setPage( 'upload' );
230 } );
231
232 return deferred;
233 };
234
235 /**
236 * Saves the stash finalizes upload. Uses
237 * {@link #getFilename getFilename}, and
238 * {@link #getText getText} to get details from
239 * the form.
240 *
241 * @protected
242 * @fires fileSaved
243 * @return {jQuery.Promise} Rejects the promise with an
244 * {@link OO.ui.Error error}, or resolves if the upload was successful.
245 */
246 mw.Upload.BookletLayout.prototype.saveFile = function () {
247 var layout = this,
248 deferred = $.Deferred();
249
250 this.upload.setFilename( this.getFilename() );
251 this.upload.setText( this.getText() );
252
253 this.uploadPromise.then( function () {
254 layout.upload.finishStashUpload().then( function () {
255 var name;
256
257 // Normalize page name and localise the 'File:' prefix
258 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
259 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
260 layout.setPage( 'insert' );
261
262 deferred.resolve();
263 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
264 }, function () {
265 var errorMessage = layout.getErrorMessageForStateDetails();
266 deferred.reject( errorMessage );
267 } );
268 } );
269
270 return deferred.promise();
271 };
272
273 /**
274 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
275 * state and state details.
276 *
277 * @protected
278 * @return {OO.ui.Error} Error to display for given state and details.
279 */
280 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
281 var message,
282 state = this.upload.getState(),
283 stateDetails = this.upload.getStateDetails(),
284 error = stateDetails.error,
285 warnings = stateDetails.upload && stateDetails.upload.warnings;
286
287 if ( state === mw.Upload.State.ERROR ) {
288 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
289 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
290 if ( error.info === 'TitleBlacklist prevents this title from being created' ) {
291 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
292 return new OO.ui.Error(
293 $( '<p>' ).html(
294 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
295 mw.message( 'api-error-blacklisted' ).parse()
296 ),
297 { recoverable: false }
298 );
299 }
300
301 message = mw.message( 'api-error-' + error.code );
302 if ( !message.exists() ) {
303 message = mw.message( 'api-error-unknownerror', JSON.stringify( stateDetails ) );
304 }
305 return new OO.ui.Error(
306 $( '<p>' ).html(
307 message.parse()
308 ),
309 { recoverable: false }
310 );
311 }
312
313 if ( state === mw.Upload.State.WARNING ) {
314 // We could get more than one of these errors, these are in order
315 // of importance. For example fixing the thumbnail like file name
316 // won't help the fact that the file already exists.
317 if ( warnings.stashfailed !== undefined ) {
318 return new OO.ui.Error(
319 $( '<p>' ).msg( 'api-error-stashfailed' ),
320 { recoverable: false }
321 );
322 } else if ( warnings.exists !== undefined ) {
323 return new OO.ui.Error(
324 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
325 { recoverable: false }
326 );
327 } else if ( warnings[ 'page-exists' ] !== undefined ) {
328 return new OO.ui.Error(
329 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
330 { recoverable: false }
331 );
332 } else if ( warnings.duplicate !== undefined ) {
333 return new OO.ui.Error(
334 $( '<p>' ).msg( 'api-error-duplicate', warnings.duplicate.length ),
335 { recoverable: false }
336 );
337 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
338 return new OO.ui.Error(
339 $( '<p>' ).msg( 'filename-thumb-name' ),
340 { recoverable: false }
341 );
342 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
343 return new OO.ui.Error(
344 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
345 { recoverable: false }
346 );
347 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
348 return new OO.ui.Error(
349 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
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.setFilename( warnings.badfilename );
356 return new OO.ui.Error(
357 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
358 );
359 } else {
360 return new OO.ui.Error(
361 $( '<p>' ).html(
362 // Let's get all the help we can if we can't pin point the error
363 mw.message( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ).parse()
364 ),
365 { recoverable: false }
366 );
367 }
368 }
369 };
370
371 /* Form renderers */
372
373 /**
374 * Renders and returns the upload form and sets the
375 * {@link #uploadForm uploadForm} property.
376 *
377 * @protected
378 * @fires selectFile
379 * @return {OO.ui.FormLayout}
380 */
381 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
382 var fieldset;
383
384 this.selectFileWidget = new OO.ui.SelectFileWidget();
385 fieldset = new OO.ui.FieldsetLayout( { label: mw.msg( 'upload-form-label-select-file' ) } );
386 fieldset.addItems( [ this.selectFileWidget ] );
387 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
388
389 // Validation
390 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
391
392 return this.uploadForm;
393 };
394
395 /**
396 * Handle change events to the upload form
397 *
398 * @protected
399 * @fires uploadValid
400 */
401 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
402 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
403 };
404
405 /**
406 * Renders and returns the information form for collecting
407 * metadata and sets the {@link #infoForm infoForm}
408 * property.
409 *
410 * @protected
411 * @return {OO.ui.FormLayout}
412 */
413 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
414 var fieldset;
415
416 this.filenameWidget = new OO.ui.TextInputWidget( {
417 indicator: 'required',
418 required: true,
419 validate: /.+/
420 } );
421 this.descriptionWidget = new OO.ui.TextInputWidget( {
422 indicator: 'required',
423 required: true,
424 validate: /\S+/,
425 multiline: true,
426 autosize: true
427 } );
428
429 fieldset = new OO.ui.FieldsetLayout( {
430 label: mw.msg( 'upload-form-label-infoform-title' )
431 } );
432 fieldset.addItems( [
433 new OO.ui.FieldLayout( this.filenameWidget, {
434 label: mw.msg( 'upload-form-label-infoform-name' ),
435 align: 'top',
436 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
437 } ),
438 new OO.ui.FieldLayout( this.descriptionWidget, {
439 label: mw.msg( 'upload-form-label-infoform-description' ),
440 align: 'top',
441 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
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 * @return {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 * @return {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 * @return {string}
514 */
515 mw.Upload.BookletLayout.prototype.getFilename = function () {
516 var filename = this.filenameWidget.getValue();
517 if ( this.filenameExtension ) {
518 filename += '.' + this.filenameExtension;
519 }
520 return filename;
521 };
522
523 /**
524 * Prefills the {@link #infoForm information form} with the given filename.
525 *
526 * @protected
527 * @param {string} filename
528 */
529 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
530 var title = mw.Title.newFromFileName( filename );
531
532 if ( title ) {
533 this.filenameWidget.setValue( title.getNameText() );
534 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
535 } else {
536 // Seems to happen for files with no extension, which should fail some checks anyway...
537 this.filenameWidget.setValue( filename );
538 this.filenameExtension = null;
539 }
540 };
541
542 /**
543 * Gets the page text from the
544 * {@link #infoForm information form}.
545 *
546 * @protected
547 * @return {string}
548 */
549 mw.Upload.BookletLayout.prototype.getText = function () {
550 return this.descriptionWidget.getValue();
551 };
552
553 /* Setters */
554
555 /**
556 * Sets the file object
557 *
558 * @protected
559 * @param {File|null} file File to select
560 */
561 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
562 this.selectFileWidget.setValue( file );
563 };
564
565 /**
566 * Clear the values of all fields
567 *
568 * @protected
569 */
570 mw.Upload.BookletLayout.prototype.clear = function () {
571 this.selectFileWidget.setValue( null );
572 this.filenameWidget.setValue( null ).setValidityFlag( true );
573 this.descriptionWidget.setValue( null ).setValidityFlag( true );
574 this.filenameUsageWidget.setValue( null );
575 };
576
577 }( jQuery, mediaWiki ) );