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