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
64 * @cfg {string} [filekey] Sets the stashed file to finish uploading. Overrides most of the file selection process, and fetches a thumbnail from the server.
66 mw
.Upload
.BookletLayout = function ( config
) {
68 mw
.Upload
.BookletLayout
.parent
.call( this, config
);
70 this.$overlay
= config
.$overlay
;
72 this.filekey
= config
.filekey
;
74 this.renderUploadForm();
75 this.renderInfoForm();
76 this.renderInsertForm();
79 new OO
.ui
.PageLayout( 'upload', {
82 content
: [ this.uploadForm
]
84 new OO
.ui
.PageLayout( 'info', {
87 content
: [ this.infoForm
]
89 new OO
.ui
.PageLayout( 'insert', {
92 content
: [ this.insertForm
]
99 OO
.inheritClass( mw
.Upload
.BookletLayout
, OO
.ui
.BookletLayout
);
104 * Progress events for the uploaded file
106 * @event fileUploadProgress
107 * @param {number} progress In percentage
108 * @param {Object} duration Duration object from `moment.duration()`
112 * The file has finished uploading
114 * @event fileUploaded
118 * The file has been saved to the database
121 * @param {Object} imageInfo See mw.Upload#getImageInfo
125 * The upload form has changed
128 * @param {boolean} isValid The form is valid
132 * The info form has changed
135 * @param {boolean} isValid The form is valid
141 * @property {OO.ui.FormLayout} uploadForm
142 * The form rendered in the first step to get the file object.
143 * Rendered in {@link #renderUploadForm renderUploadForm}.
147 * @property {OO.ui.FormLayout} infoForm
148 * The form rendered in the second step to get metadata.
149 * Rendered in {@link #renderInfoForm renderInfoForm}
153 * @property {OO.ui.FormLayout} insertForm
154 * The form rendered in the third step to show usage
155 * Rendered in {@link #renderInsertForm renderInsertForm}
161 * Initialize for a new upload
163 * @return {jQuery.Promise} Promise resolved when everything is initialized
165 mw
.Upload
.BookletLayout
.prototype.initialize = function () {
169 this.upload
= this.createUpload();
171 this.setPage( 'upload' );
173 if ( this.filekey
) {
174 this.setFilekey( this.filekey
);
177 return this.upload
.getApi().then(
179 // If the user can't upload anything, don't give them the option to.
180 return api
.getUserInfo().then(
181 function ( userInfo
) {
182 if ( userInfo
.rights
.indexOf( 'upload' ) === -1 ) {
183 // TODO Use a better error message when not all logged-in users can upload
184 booklet
.getPage( 'upload' ).$element
.msg( 'api-error-mustbeloggedin' );
186 return $.Deferred().resolve();
189 return $.Deferred().resolve();
193 function ( errorMsg
) {
194 booklet
.getPage( 'upload' ).$element
.msg( errorMsg
);
195 return $.Deferred().resolve();
201 * Create a new upload model
204 * @return {mw.Upload} Upload model
206 mw
.Upload
.BookletLayout
.prototype.createUpload = function () {
207 return new mw
.Upload();
213 * Uploads the file that was added in the upload form. Uses
214 * {@link #getFile getFile} to get the HTML5
218 * @fires fileUploadProgress
219 * @fires fileUploaded
220 * @return {jQuery.Promise}
222 mw
.Upload
.BookletLayout
.prototype.uploadFile = function () {
223 var deferred
= $.Deferred(),
224 startTime
= new Date(),
226 file
= this.getFile();
228 this.setPage( 'info' );
230 if ( this.filekey
) {
231 if ( file
=== null ) {
232 // Someone gonna get-a hurt real bad
233 throw new Error( 'filekey not passed into file select widget, which is impossible. Quitting while we\'re behind.' );
236 // Stashed file already uploaded.
238 this.uploadPromise
= deferred
;
239 this.emit( 'fileUploaded' );
243 this.setFilename( file
.name
);
245 this.upload
.setFile( file
);
246 // The original file name might contain invalid characters, so use our sanitized one
247 this.upload
.setFilename( this.getFilename() );
249 this.uploadPromise
= this.upload
.uploadToStash();
250 this.uploadPromise
.then( function () {
252 layout
.emit( 'fileUploaded' );
254 // These errors will be thrown while the user is on the info page.
255 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
256 // really be an error...
257 var errorMessage
= layout
.getErrorMessageForStateDetails();
258 deferred
.reject( errorMessage
);
259 }, function ( progress
) {
260 var elapsedTime
= new Date() - startTime
,
261 estimatedTotalTime
= ( 1 / progress
) * elapsedTime
,
262 estimatedRemainingTime
= moment
.duration( estimatedTotalTime
- elapsedTime
);
263 layout
.emit( 'fileUploadProgress', progress
, estimatedRemainingTime
);
266 // If there is an error in uploading, come back to the upload page
267 deferred
.fail( function () {
268 layout
.setPage( 'upload' );
275 * Saves the stash finalizes upload. Uses
276 * {@link #getFilename getFilename}, and
277 * {@link #getText getText} to get details from
282 * @return {jQuery.Promise} Rejects the promise with an
283 * {@link OO.ui.Error error}, or resolves if the upload was successful.
285 mw
.Upload
.BookletLayout
.prototype.saveFile = function () {
287 deferred
= $.Deferred();
289 this.upload
.setFilename( this.getFilename() );
290 this.upload
.setText( this.getText() );
292 this.uploadPromise
.then( function () {
293 layout
.upload
.finishStashUpload().then( function () {
296 // Normalize page name and localise the 'File:' prefix
297 name
= new mw
.Title( 'File:' + layout
.upload
.getFilename() ).toString();
298 layout
.filenameUsageWidget
.setValue( '[[' + name
+ ']]' );
299 layout
.setPage( 'insert' );
302 layout
.emit( 'fileSaved', layout
.upload
.getImageInfo() );
304 var errorMessage
= layout
.getErrorMessageForStateDetails();
305 deferred
.reject( errorMessage
);
309 return deferred
.promise();
313 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
314 * state and state details.
317 * @return {OO.ui.Error} Error to display for given state and details.
319 mw
.Upload
.BookletLayout
.prototype.getErrorMessageForStateDetails = function () {
321 state
= this.upload
.getState(),
322 stateDetails
= this.upload
.getStateDetails(),
323 error
= stateDetails
.error
,
324 warnings
= stateDetails
.upload
&& stateDetails
.upload
.warnings
;
326 if ( state
=== mw
.Upload
.State
.ERROR
) {
328 // If there's an 'exception' key, this might be a timeout, or other connection problem
329 return new OO
.ui
.Error(
330 $( '<p>' ).msg( 'api-error-unknownerror', JSON
.stringify( stateDetails
) ),
331 { recoverable
: false }
335 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
336 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
337 if ( error
.info
=== 'TitleBlacklist prevents this title from being created' ) {
338 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
339 return new OO
.ui
.Error(
340 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
341 $( '<p>' ).msg( 'api-error-blacklisted' ),
342 { recoverable
: false }
346 message
= mw
.message( 'api-error-' + error
.code
);
347 if ( !message
.exists() ) {
348 message
= mw
.message( 'api-error-unknownerror', JSON
.stringify( stateDetails
) );
350 return new OO
.ui
.Error(
351 $( '<p>' ).append( message
.parseDom() ),
352 { recoverable
: false }
356 if ( state
=== mw
.Upload
.State
.WARNING
) {
357 // We could get more than one of these errors, these are in order
358 // of importance. For example fixing the thumbnail like file name
359 // won't help the fact that the file already exists.
360 if ( warnings
.stashfailed
!== undefined ) {
361 return new OO
.ui
.Error(
362 $( '<p>' ).msg( 'api-error-stashfailed' ),
363 { recoverable
: false }
365 } else if ( warnings
.exists
!== undefined ) {
366 return new OO
.ui
.Error(
367 $( '<p>' ).msg( 'fileexists', 'File:' + warnings
.exists
),
368 { recoverable
: false }
370 } else if ( warnings
[ 'page-exists' ] !== undefined ) {
371 return new OO
.ui
.Error(
372 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings
[ 'page-exists' ] ),
373 { recoverable
: false }
375 } else if ( warnings
.duplicate
!== undefined ) {
376 return new OO
.ui
.Error(
377 $( '<p>' ).msg( 'api-error-duplicate', warnings
.duplicate
.length
),
378 { recoverable
: false }
380 } else if ( warnings
[ 'thumb-name' ] !== undefined ) {
381 return new OO
.ui
.Error(
382 $( '<p>' ).msg( 'filename-thumb-name' ),
383 { recoverable
: false }
385 } else if ( warnings
[ 'bad-prefix' ] !== undefined ) {
386 return new OO
.ui
.Error(
387 $( '<p>' ).msg( 'filename-bad-prefix', warnings
[ 'bad-prefix' ] ),
388 { recoverable
: false }
390 } else if ( warnings
[ 'duplicate-archive' ] !== undefined ) {
391 return new OO
.ui
.Error(
392 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
393 { recoverable
: false }
395 } else if ( warnings
.badfilename
!== undefined ) {
396 // Change the name if the current name isn't acceptable
397 // TODO This might not really be the best place to do this
398 this.setFilename( warnings
.badfilename
);
399 return new OO
.ui
.Error(
400 $( '<p>' ).msg( 'badfilename', warnings
.badfilename
)
403 return new OO
.ui
.Error(
404 // Let's get all the help we can if we can't pin point the error
405 $( '<p>' ).msg( 'api-error-unknown-warning', JSON
.stringify( stateDetails
) ),
406 { recoverable
: false }
415 * Renders and returns the upload form and sets the
416 * {@link #uploadForm uploadForm} property.
420 * @return {OO.ui.FormLayout}
422 mw
.Upload
.BookletLayout
.prototype.renderUploadForm = function () {
426 this.selectFileWidget
= this.getFileWidget();
427 fieldset
= new OO
.ui
.FieldsetLayout();
428 fieldset
.addItems( [ this.selectFileWidget
] );
429 this.uploadForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
431 // Validation (if the SFW is for a stashed file, this never fires)
432 this.selectFileWidget
.on( 'change', this.onUploadFormChange
.bind( this ) );
434 this.selectFileWidget
.on( 'change', function () {
435 layout
.updateFilePreview();
438 return this.uploadForm
;
442 * Gets the widget for displaying or inputting the file to upload.
444 * @return {OO.ui.SelectFileWidget|mw.widgets.StashedFileWidget}
446 mw
.Upload
.BookletLayout
.prototype.getFileWidget = function () {
447 if ( this.filekey
) {
448 return new mw
.widgets
.StashedFileWidget( {
449 filekey
: this.filekey
453 return new OO
.ui
.SelectFileWidget( {
459 * Updates the file preview on the info form when a file is added.
463 mw
.Upload
.BookletLayout
.prototype.updateFilePreview = function () {
464 this.selectFileWidget
.loadAndGetImageUrl().done( function ( url
) {
465 this.filePreview
.$element
.find( 'p' ).remove();
466 this.filePreview
.$element
.css( 'background-image', 'url(' + url
+ ')' );
467 this.infoForm
.$element
.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
468 }.bind( this ) ).fail( function () {
469 this.filePreview
.$element
.find( 'p' ).remove();
470 if ( this.selectFileWidget
.getValue() ) {
471 this.filePreview
.$element
.append(
472 $( '<p>' ).text( this.selectFileWidget
.getValue().name
)
475 this.filePreview
.$element
.css( 'background-image', '' );
476 this.infoForm
.$element
.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
481 * Handle change events to the upload form
486 mw
.Upload
.BookletLayout
.prototype.onUploadFormChange = function () {
487 this.emit( 'uploadValid', !!this.selectFileWidget
.getValue() );
491 * Renders and returns the information form for collecting
492 * metadata and sets the {@link #infoForm infoForm}
496 * @return {OO.ui.FormLayout}
498 mw
.Upload
.BookletLayout
.prototype.renderInfoForm = function () {
501 this.filePreview
= new OO
.ui
.Widget( {
502 classes
: [ 'mw-upload-bookletLayout-filePreview' ]
504 this.progressBarWidget
= new OO
.ui
.ProgressBarWidget( {
507 this.filePreview
.$element
.append( this.progressBarWidget
.$element
);
509 this.filenameWidget
= new OO
.ui
.TextInputWidget( {
510 indicator
: 'required',
514 this.descriptionWidget
= new OO
.ui
.TextInputWidget( {
515 indicator
: 'required',
522 fieldset
= new OO
.ui
.FieldsetLayout( {
523 label
: mw
.msg( 'upload-form-label-infoform-title' )
526 new OO
.ui
.FieldLayout( this.filenameWidget
, {
527 label
: mw
.msg( 'upload-form-label-infoform-name' ),
529 help
: mw
.msg( 'upload-form-label-infoform-name-tooltip' )
531 new OO
.ui
.FieldLayout( this.descriptionWidget
, {
532 label
: mw
.msg( 'upload-form-label-infoform-description' ),
534 help
: mw
.msg( 'upload-form-label-infoform-description-tooltip' )
537 this.infoForm
= new OO
.ui
.FormLayout( {
538 classes
: [ 'mw-upload-bookletLayout-infoForm' ],
539 items
: [ this.filePreview
, fieldset
]
542 this.on( 'fileUploadProgress', function ( progress
) {
543 this.progressBarWidget
.setProgress( progress
* 100 );
546 this.filenameWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
547 this.descriptionWidget
.on( 'change', this.onInfoFormChange
.bind( this ) );
549 return this.infoForm
;
553 * Handle change events to the info form
558 mw
.Upload
.BookletLayout
.prototype.onInfoFormChange = function () {
561 this.filenameWidget
.getValidity(),
562 this.descriptionWidget
.getValidity()
563 ).done( function () {
564 layout
.emit( 'infoValid', true );
565 } ).fail( function () {
566 layout
.emit( 'infoValid', false );
571 * Renders and returns the insert form to show file usage and
572 * sets the {@link #insertForm insertForm} property.
575 * @return {OO.ui.FormLayout}
577 mw
.Upload
.BookletLayout
.prototype.renderInsertForm = function () {
580 this.filenameUsageWidget
= new OO
.ui
.TextInputWidget();
581 fieldset
= new OO
.ui
.FieldsetLayout( {
582 label
: mw
.msg( 'upload-form-label-usage-title' )
585 new OO
.ui
.FieldLayout( this.filenameUsageWidget
, {
586 label
: mw
.msg( 'upload-form-label-usage-filename' ),
590 this.insertForm
= new OO
.ui
.FormLayout( { items
: [ fieldset
] } );
592 return this.insertForm
;
598 * Gets the file object from the
599 * {@link #uploadForm upload form}.
602 * @return {File|null}
604 mw
.Upload
.BookletLayout
.prototype.getFile = function () {
605 return this.selectFileWidget
.getValue();
609 * Gets the file name from the
610 * {@link #infoForm information form}.
615 mw
.Upload
.BookletLayout
.prototype.getFilename = function () {
616 var filename
= this.filenameWidget
.getValue();
617 if ( this.filenameExtension
) {
618 filename
+= '.' + this.filenameExtension
;
624 * Prefills the {@link #infoForm information form} with the given filename.
627 * @param {string} filename
629 mw
.Upload
.BookletLayout
.prototype.setFilename = function ( filename
) {
630 var title
= mw
.Title
.newFromFileName( filename
);
633 this.filenameWidget
.setValue( title
.getNameText() );
634 this.filenameExtension
= mw
.Title
.normalizeExtension( title
.getExtension() );
636 // Seems to happen for files with no extension, which should fail some checks anyway...
637 this.filenameWidget
.setValue( filename
);
638 this.filenameExtension
= null;
643 * Gets the page text from the
644 * {@link #infoForm information form}.
649 mw
.Upload
.BookletLayout
.prototype.getText = function () {
650 return this.descriptionWidget
.getValue();
656 * Sets the file object
659 * @param {File|null} file File to select
661 mw
.Upload
.BookletLayout
.prototype.setFile = function ( file
) {
662 this.selectFileWidget
.setValue( file
);
666 * Sets the filekey of a file already stashed on the server
667 * as the target of this upload operation.
670 * @param {string} filekey
672 mw
.Upload
.BookletLayout
.prototype.setFilekey = function ( filekey
) {
673 this.upload
.setFilekey( this.filekey
);
674 this.selectFileWidget
.setValue( filekey
);
676 this.onUploadFormChange();
680 * Clear the values of all fields
684 mw
.Upload
.BookletLayout
.prototype.clear = function () {
685 this.selectFileWidget
.setValue( null );
686 this.progressBarWidget
.setProgress( 0 );
687 this.filenameWidget
.setValue( null ).setValidityFlag( true );
688 this.descriptionWidget
.setValue( null ).setValidityFlag( true );
689 this.filenameUsageWidget
.setValue( null );
692 }( jQuery
, mediaWiki
, moment
) );