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