2 ( function ( $, mw
, moment
) {
5 * mw.Upload.BookletLayout encapsulates the process of uploading a file
6 * to MediaWiki using the {@link mw.Upload upload model}.
7 * The booklet emits events that can be used to get the stashed
8 * upload and the final file. It can be extended to accept
9 * additional fields from the user for specific scenarios like
10 * for Commons, or campaigns.
14 * The {@link OO.ui.BookletLayout booklet layout} has three steps:
16 * - **Upload**: Has a {@link OO.ui.SelectFileWidget field} to get the file object.
18 * - **Information**: Has a {@link OO.ui.FormLayout form} to collect metadata. This can be
21 * - **Insert**: Has details on how to use the file that was uploaded.
23 * Each step has a form associated with it defined in
24 * {@link #renderUploadForm renderUploadForm},
25 * {@link #renderInfoForm renderInfoForm}, and
26 * {@link #renderInsertForm renderInfoForm}. The
27 * {@link #getFile getFile},
28 * {@link #getFilename getFilename}, and
29 * {@link #getText getText} methods are used to get
30 * the information filled in these forms, required to call
31 * {@link mw.Upload mw.Upload}.
35 * See the {@link mw.Upload.Dialog upload dialog}.
37 * The {@link #event-fileUploaded fileUploaded},
38 * and {@link #event-fileSaved fileSaved} events can
39 * be used to get details of the upload.
43 * To extend using {@link mw.Upload mw.Upload}, override
44 * {@link #renderInfoForm renderInfoForm} to render
45 * the form required for the specific use-case. Update the
46 * {@link #getFilename getFilename}, and
47 * {@link #getText getText} methods to return data
48 * from your newly created form. If you added new fields you'll also have
49 * to update the {@link #clear} method.
51 * If you plan to use a different upload model, apart from what is mentioned
52 * above, you'll also have to override the
53 * {@link #createUpload createUpload} method to
54 * return the new model. The {@link #saveFile saveFile}, and
55 * the {@link #uploadFile uploadFile} methods need to be
56 * overridden to use the new model and data returned from the forms.
59 * @extends OO.ui.BookletLayout
62 * @param {Object} config Configuration options
63 * @cfg {jQuery} [$overlay] Overlay to use for widgets in the booklet
65 mw
.Upload
.BookletLayout = function ( config
) {
67 mw
.Upload
.BookletLayout
.parent
.call( this, config
);
69 this.$overlay
= config
.$overlay
;
71 this.renderUploadForm();
72 this.renderInfoForm();
73 this.renderInsertForm();
76 new OO
.ui
.PageLayout( 'upload', {
79 content
: [ this.uploadForm
]
81 new OO
.ui
.PageLayout( 'info', {
84 content
: [ this.infoForm
]
86 new OO
.ui
.PageLayout( 'insert', {
89 content
: [ this.insertForm
]
96 OO
.inheritClass( mw
.Upload
.BookletLayout
, OO
.ui
.BookletLayout
);
101 * Progress events for the uploaded file
103 * @event fileUploadProgress
104 * @param {number} progress In percentage
105 * @param {Object} duration Duration object from `moment.duration()`
109 * The file has finished uploading
111 * @event fileUploaded
115 * The file has been saved to the database
118 * @param {Object} imageInfo See mw.Upload#getImageInfo
122 * The upload form has changed
125 * @param {boolean} isValid The form is valid
129 * The info form has changed
132 * @param {boolean} isValid The form is valid
138 * @property {OO.ui.FormLayout} uploadForm
139 * The form rendered in the first step to get the file object.
140 * Rendered in {@link #renderUploadForm renderUploadForm}.
144 * @property {OO.ui.FormLayout} infoForm
145 * The form rendered in the second step to get metadata.
146 * Rendered in {@link #renderInfoForm renderInfoForm}
150 * @property {OO.ui.FormLayout} insertForm
151 * The form rendered in the third step to show usage
152 * Rendered in {@link #renderInsertForm renderInsertForm}
158 * Initialize for a new upload
160 * @return {jQuery.Promise} Promise resolved when everything is initialized
162 mw
.Upload
.BookletLayout
.prototype.initialize = function () {
166 this.upload
= this.createUpload();
167 this.setPage( 'upload' );
169 return this.upload
.getApi().then(
171 // If the user can't upload anything, don't give them the option to.
172 return api
.getUserInfo().then(
173 function ( userInfo
) {
174 if ( userInfo
.rights
.indexOf( 'upload' ) === -1 ) {
175 // TODO Use a better error message when not all logged-in users can upload
176 booklet
.getPage( 'upload' ).$element
.msg( 'api-error-mustbeloggedin' );
178 return $.Deferred().resolve();
181 return $.Deferred().resolve();
185 function ( errorMsg
) {
186 booklet
.getPage( 'upload' ).$element
.msg( errorMsg
);
187 return $.Deferred().resolve();
193 * Create a new upload model
196 * @return {mw.Upload} Upload model
198 mw
.Upload
.BookletLayout
.prototype.createUpload = function () {
199 return new mw
.Upload();
205 * Uploads the file that was added in the upload form. Uses
206 * {@link #getFile getFile} to get the HTML5
210 * @fires fileUploadProgress
211 * @fires fileUploaded
212 * @return {jQuery.Promise}
214 mw
.Upload
.BookletLayout
.prototype.uploadFile = function () {
215 var deferred
= $.Deferred(),
216 startTime
= new Date(),
218 file
= this.getFile();
220 this.setFilename( file
.name
);
222 this.setPage( 'info' );
224 this.upload
.setFile( file
);
225 // The original file name might contain invalid characters, so use our sanitized one
226 this.upload
.setFilename( this.getFilename() );
228 this.uploadPromise
= this.upload
.uploadToStash();
229 this.uploadPromise
.then( function () {
231 layout
.emit( 'fileUploaded' );
233 // These errors will be thrown while the user is on the info page.
234 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
235 // really be an error...
236 var errorMessage
= layout
.getErrorMessageForStateDetails();
237 deferred
.reject( errorMessage
);
238 }, function ( progress
) {
239 var elapsedTime
= new Date() - startTime
,
240 estimatedTotalTime
= ( 1 / progress
) * elapsedTime
,
241 estimatedRemainingTime
= moment
.duration( estimatedTotalTime
- elapsedTime
);
242 layout
.emit( 'fileUploadProgress', progress
, estimatedRemainingTime
);
245 // If there is an error in uploading, come back to the upload page
246 deferred
.fail( function () {
247 layout
.setPage( 'upload' );
254 * Saves the stash finalizes upload. Uses
255 * {@link #getFilename getFilename}, and
256 * {@link #getText getText} to get details from
261 * @return {jQuery.Promise} Rejects the promise with an
262 * {@link OO.ui.Error error}, or resolves if the upload was successful.
264 mw
.Upload
.BookletLayout
.prototype.saveFile = function () {
266 deferred
= $.Deferred();
268 this.upload
.setFilename( this.getFilename() );
269 this.upload
.setText( this.getText() );
271 this.uploadPromise
.then( function () {
272 layout
.upload
.finishStashUpload().then( function () {
275 // Normalize page name and localise the 'File:' prefix
276 name
= new mw
.Title( 'File:' + layout
.upload
.getFilename() ).toString();
277 layout
.filenameUsageWidget
.setValue( '[[' + name
+ ']]' );
278 layout
.setPage( 'insert' );
281 layout
.emit( 'fileSaved', layout
.upload
.getImageInfo() );
283 var errorMessage
= layout
.getErrorMessageForStateDetails();
284 deferred
.reject( errorMessage
);
288 return deferred
.promise();
292 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
293 * state and state details.
296 * @return {OO.ui.Error} Error to display for given state and details.
298 mw
.Upload
.BookletLayout
.prototype.getErrorMessageForStateDetails = function () {
300 state
= this.upload
.getState(),
301 stateDetails
= this.upload
.getStateDetails(),
302 error
= stateDetails
.error
,
303 warnings
= stateDetails
.upload
&& stateDetails
.upload
.warnings
;
305 if ( state
=== mw
.Upload
.State
.ERROR
) {
307 // If there's an 'exception' key, this might be a timeout, or other connection problem
308 return new OO
.ui
.Error(
309 $( '<p>' ).msg( 'api-error-unknownerror', JSON
.stringify( stateDetails
) ),
310 { recoverable
: false }
314 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
315 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
316 if ( error
.info
=== 'TitleBlacklist prevents this title from being created' ) {
317 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
318 return new OO
.ui
.Error(
319 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
320 $( '<p>' ).msg( 'api-error-blacklisted' ),
321 { recoverable
: false }
325 message
= mw
.message( 'api-error-' + error
.code
);
326 if ( !message
.exists() ) {
327 message
= mw
.message( 'api-error-unknownerror', JSON
.stringify( stateDetails
) );
329 return new OO
.ui
.Error(
330 $( '<p>' ).append( message
.parseDom() ),
331 { recoverable
: false }
335 if ( state
=== mw
.Upload
.State
.WARNING
) {
336 // We could get more than one of these errors, these are in order
337 // of importance. For example fixing the thumbnail like file name
338 // won't help the fact that the file already exists.
339 if ( warnings
.stashfailed
!== undefined ) {
340 return new OO
.ui
.Error(
341 $( '<p>' ).msg( 'api-error-stashfailed' ),
342 { recoverable
: false }
344 } else if ( warnings
.exists
!== undefined ) {
345 return new OO
.ui
.Error(
346 $( '<p>' ).msg( 'fileexists', 'File:' + warnings
.exists
),
347 { recoverable
: false }
349 } else if ( warnings
[ 'page-exists' ] !== undefined ) {
350 return new OO
.ui
.Error(
351 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings
[ 'page-exists' ] ),
352 { recoverable
: false }
354 } else if ( warnings
.duplicate
!== undefined ) {
355 return new OO
.ui
.Error(
356 $( '<p>' ).msg( 'api-error-duplicate', warnings
.duplicate
.length
),
357 { recoverable
: false }
359 } else if ( warnings
[ 'thumb-name' ] !== undefined ) {
360 return new OO
.ui
.Error(
361 $( '<p>' ).msg( 'filename-thumb-name' ),
362 { recoverable
: false }
364 } else if ( warnings
[ 'bad-prefix' ] !== undefined ) {
365 return new OO
.ui
.Error(
366 $( '<p>' ).msg( 'filename-bad-prefix', warnings
[ 'bad-prefix' ] ),
367 { recoverable
: false }
369 } else if ( warnings
[ 'duplicate-archive' ] !== undefined ) {
370 return new OO
.ui
.Error(
371 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
372 { recoverable
: false }
374 } else if ( warnings
.badfilename
!== undefined ) {
375 // Change the name if the current name isn't acceptable
376 // TODO This might not really be the best place to do this
377 this.setFilename( warnings
.badfilename
);
378 return new OO
.ui
.Error(
379 $( '<p>' ).msg( 'badfilename', warnings
.badfilename
)
382 return new OO
.ui
.Error(
383 // Let's get all the help we can if we can't pin point the error
384 $( '<p>' ).msg( 'api-error-unknown-warning', JSON
.stringify( stateDetails
) ),
385 { recoverable
: false }
394 * Renders and returns the upload form and sets the
395 * {@link #uploadForm uploadForm} property.
399 * @return {OO.ui.FormLayout}
401 mw
.Upload
.BookletLayout
.prototype.renderUploadForm = function () {
405 this.selectFileWidget
= new OO
.ui
.SelectFileWidget( {
408 fieldset
= new OO
.ui
.FieldsetLayout();
409 fieldset
.addItems( [ this.selectFileWidget
] );
410 this.uploadForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
413 this.selectFileWidget
.on( 'change', this.onUploadFormChange
.bind( this ) );
415 this.selectFileWidget
.on( 'change', function () {
416 layout
.updateFilePreview();
419 return this.uploadForm
;
423 * Updates the file preview on the info form when a file is added.
427 mw
.Upload
.BookletLayout
.prototype.updateFilePreview = function () {
428 this.selectFileWidget
.loadAndGetImageUrl().done( function ( url
) {
429 this.filePreview
.$element
.find( 'p' ).remove();
430 this.filePreview
.$element
.css( 'background-image', 'url(' + url
+ ')' );
431 this.infoForm
.$element
.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
432 }.bind( this ) ).fail( function () {
433 this.filePreview
.$element
.find( 'p' ).remove();
434 if ( this.selectFileWidget
.getValue() ) {
435 this.filePreview
.$element
.append(
436 $( '<p>' ).text( this.selectFileWidget
.getValue().name
)
439 this.filePreview
.$element
.css( 'background-image', '' );
440 this.infoForm
.$element
.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
445 * Handle change events to the upload form
450 mw
.Upload
.BookletLayout
.prototype.onUploadFormChange = function () {
451 this.emit( 'uploadValid', !!this.selectFileWidget
.getValue() );
455 * Renders and returns the information form for collecting
456 * metadata and sets the {@link #infoForm infoForm}
460 * @return {OO.ui.FormLayout}
462 mw
.Upload
.BookletLayout
.prototype.renderInfoForm = function () {
465 this.filePreview
= new OO
.ui
.Widget( {
466 classes
: [ 'mw-upload-bookletLayout-filePreview' ]
468 this.progressBarWidget
= new OO
.ui
.ProgressBarWidget( {
471 this.filePreview
.$element
.append( this.progressBarWidget
.$element
);
473 this.filenameWidget
= new OO
.ui
.TextInputWidget( {
474 indicator
: 'required',
478 this.descriptionWidget
= new OO
.ui
.TextInputWidget( {
479 indicator
: 'required',
486 fieldset
= new OO
.ui
.FieldsetLayout( {
487 label
: mw
.msg( 'upload-form-label-infoform-title' )
490 new OO
.ui
.FieldLayout( this.filenameWidget
, {
491 label
: mw
.msg( 'upload-form-label-infoform-name' ),
493 help
: mw
.msg( 'upload-form-label-infoform-name-tooltip' )
495 new OO
.ui
.FieldLayout( this.descriptionWidget
, {
496 label
: mw
.msg( 'upload-form-label-infoform-description' ),
498 help
: mw
.msg( 'upload-form-label-infoform-description-tooltip' )
501 this.infoForm
= new OO
.ui
.FormLayout( {
502 classes
: [ 'mw-upload-bookletLayout-infoForm' ],
503 items
: [ this.filePreview
, fieldset
]
506 this.on( 'fileUploadProgress', function ( progress
) {
507 this.progressBarWidget
.setProgress( progress
* 100 );
510 this.filenameWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
511 this.descriptionWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
513 return this.infoForm
;
517 * Handle change events to the info form
522 mw
.Upload
.BookletLayout
.prototype.onInfoFormChange = function () {
525 this.filenameWidget
.getValidity(),
526 this.descriptionWidget
.getValidity()
527 ).done( function () {
528 layout
.emit( 'infoValid', true );
529 } ).fail( function () {
530 layout
.emit( 'infoValid', false );
535 * Renders and returns the insert form to show file usage and
536 * sets the {@link #insertForm insertForm} property.
539 * @return {OO.ui.FormLayout}
541 mw
.Upload
.BookletLayout
.prototype.renderInsertForm = function () {
544 this.filenameUsageWidget
= new OO
.ui
.TextInputWidget();
545 fieldset
= new OO
.ui
.FieldsetLayout( {
546 label
: mw
.msg( 'upload-form-label-usage-title' )
549 new OO
.ui
.FieldLayout( this.filenameUsageWidget
, {
550 label
: mw
.msg( 'upload-form-label-usage-filename' ),
554 this.insertForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
556 return this.insertForm
;
562 * Gets the file object from the
563 * {@link #uploadForm upload form}.
566 * @return {File|null}
568 mw
.Upload
.BookletLayout
.prototype.getFile = function () {
569 return this.selectFileWidget
.getValue();
573 * Gets the file name from the
574 * {@link #infoForm information form}.
579 mw
.Upload
.BookletLayout
.prototype.getFilename = function () {
580 var filename
= this.filenameWidget
.getValue();
581 if ( this.filenameExtension
) {
582 filename
+= '.' + this.filenameExtension
;
588 * Prefills the {@link #infoForm information form} with the given filename.
591 * @param {string} filename
593 mw
.Upload
.BookletLayout
.prototype.setFilename = function ( filename
) {
594 var title
= mw
.Title
.newFromFileName( filename
);
597 this.filenameWidget
.setValue( title
.getNameText() );
598 this.filenameExtension
= mw
.Title
.normalizeExtension( title
.getExtension() );
600 // Seems to happen for files with no extension, which should fail some checks anyway...
601 this.filenameWidget
.setValue( filename
);
602 this.filenameExtension
= null;
607 * Gets the page text from the
608 * {@link #infoForm information form}.
613 mw
.Upload
.BookletLayout
.prototype.getText = function () {
614 return this.descriptionWidget
.getValue();
620 * Sets the file object
623 * @param {File|null} file File to select
625 mw
.Upload
.BookletLayout
.prototype.setFile = function ( file
) {
626 this.selectFileWidget
.setValue( file
);
630 * Clear the values of all fields
634 mw
.Upload
.BookletLayout
.prototype.clear = function () {
635 this.selectFileWidget
.setValue( null );
636 this.progressBarWidget
.setProgress( 0 );
637 this.filenameWidget
.setValue( null ).setValidityFlag( true );
638 this.descriptionWidget
.setValue( null ).setValidityFlag( true );
639 this.filenameUsageWidget
.setValue( null );
642 }( jQuery
, mediaWiki
, moment
) );