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 if ( mw.user.isAnon() ) {
184 booklet.getPage( 'upload' ).$element.msg( 'apierror-mustbeloggedin', mw.msg( 'action-upload' ) );
186 booklet.getPage( 'upload' ).$element.msg( 'apierror-permissiondenied', mw.msg( 'action-upload' ) );
189 return $.Deferred().resolve();
191 // Always resolve, never reject
192 function () { return $.Deferred().resolve(); }
195 function ( errorMsg ) {
196 booklet.getPage( 'upload' ).$element.msg( errorMsg );
197 return $.Deferred().resolve();
203 * Create a new upload model
206 * @return {mw.Upload} Upload model
208 mw.Upload.BookletLayout.prototype.createUpload = function () {
209 return new mw.Upload( {
212 errorlang: mw.config.get( 'wgUserLanguage' ),
222 * Uploads the file that was added in the upload form. Uses
223 * {@link #getFile getFile} to get the HTML5
227 * @fires fileUploadProgress
228 * @fires fileUploaded
229 * @return {jQuery.Promise}
231 mw.Upload.BookletLayout.prototype.uploadFile = function () {
232 var deferred = $.Deferred(),
233 startTime = new Date(),
235 file = this.getFile();
237 this.setPage( 'info' );
239 if ( this.filekey ) {
240 if ( file === null ) {
241 // Someone gonna get-a hurt real bad
242 throw new Error( 'filekey not passed into file select widget, which is impossible. Quitting while we\'re behind.' );
245 // Stashed file already uploaded.
247 this.uploadPromise = deferred;
248 this.emit( 'fileUploaded' );
252 this.setFilename( file.name );
254 this.upload.setFile( file );
255 // The original file name might contain invalid characters, so use our sanitized one
256 this.upload.setFilename( this.getFilename() );
258 this.uploadPromise = this.upload.uploadToStash();
259 this.uploadPromise.then( function () {
261 layout.emit( 'fileUploaded' );
263 // These errors will be thrown while the user is on the info page.
264 layout.getErrorMessageForStateDetails().then( function ( errorMessage ) {
265 deferred.reject( errorMessage );
267 }, function ( progress ) {
268 var elapsedTime = new Date() - startTime,
269 estimatedTotalTime = ( 1 / progress ) * elapsedTime,
270 estimatedRemainingTime = moment.duration( estimatedTotalTime - elapsedTime );
271 layout.emit( 'fileUploadProgress', progress, estimatedRemainingTime );
274 // If there is an error in uploading, come back to the upload page
275 deferred.fail( function () {
276 layout.setPage( 'upload' );
283 * Saves the stash finalizes upload. Uses
284 * {@link #getFilename getFilename}, and
285 * {@link #getText getText} to get details from
290 * @return {jQuery.Promise} Rejects the promise with an
291 * {@link OO.ui.Error error}, or resolves if the upload was successful.
293 mw.Upload.BookletLayout.prototype.saveFile = function () {
295 deferred = $.Deferred();
297 this.upload.setFilename( this.getFilename() );
298 this.upload.setText( this.getText() );
300 this.uploadPromise.then( function () {
301 layout.upload.finishStashUpload().then( function () {
304 // Normalize page name and localise the 'File:' prefix
305 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
306 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
307 layout.setPage( 'insert' );
310 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
312 layout.getErrorMessageForStateDetails().then( function ( errorMessage ) {
313 deferred.reject( errorMessage );
318 return deferred.promise();
322 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
323 * state and state details.
326 * @return {jQuery.Promise} A Promise that will be resolved with an OO.ui.Error.
328 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
329 var state = this.upload.getState(),
330 stateDetails = this.upload.getStateDetails(),
331 error = stateDetails.errors ? stateDetails.errors[ 0 ] : false,
332 warnings = stateDetails.upload && stateDetails.upload.warnings,
335 if ( state === mw.Upload.State.ERROR ) {
337 // If there's an 'exception' key, this might be a timeout, or other connection problem
338 return $.Deferred().resolve( new OO.ui.Error(
339 $( '<p>' ).msg( 'apierror-unknownerror', JSON.stringify( stateDetails ) ),
340 { recoverable: false }
344 return $.Deferred().resolve( new OO.ui.Error(
345 $( '<p>' ).html( error.html ),
346 { recoverable: false }
350 if ( state === mw.Upload.State.WARNING ) {
351 // We could get more than one of these errors, these are in order
352 // of importance. For example fixing the thumbnail like file name
353 // won't help the fact that the file already exists.
354 if ( warnings.exists !== undefined ) {
355 return $.Deferred().resolve( new OO.ui.Error(
356 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
357 { recoverable: false }
359 } else if ( warnings[ 'exists-normalized' ] !== undefined ) {
360 return $.Deferred().resolve( new OO.ui.Error(
361 $( '<p>' ).msg( 'fileexists', 'File:' + warnings[ 'exists-normalized' ] ),
362 { recoverable: false }
364 } else if ( warnings[ 'page-exists' ] !== undefined ) {
365 return $.Deferred().resolve( new OO.ui.Error(
366 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
367 { recoverable: false }
369 } else if ( warnings.duplicate !== undefined ) {
370 $.each( warnings.duplicate, function ( i, filename ) {
371 var $a = $( '<a>' ).text( filename ),
372 href = mw.Title.makeTitle( mw.config.get( 'wgNamespaceIds' ).file, filename ).getUrl( {} );
374 $a.attr( { href: href, target: '_blank' } );
375 $ul.append( $( '<li>' ).append( $a ) );
378 return $.Deferred().resolve( new OO.ui.Error(
379 $( '<p>' ).msg( 'file-exists-duplicate', warnings.duplicate.length ).append( $ul ),
380 { recoverable: false }
382 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
383 return $.Deferred().resolve( new OO.ui.Error(
384 $( '<p>' ).msg( 'filename-thumb-name' ),
385 { recoverable: false }
387 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
388 return $.Deferred().resolve( new OO.ui.Error(
389 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
390 { recoverable: false }
392 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
393 return $.Deferred().resolve( new OO.ui.Error(
394 $( '<p>' ).msg( 'file-deleted-duplicate', 'File:' + warnings[ 'duplicate-archive' ] ),
395 { recoverable: false }
397 } else if ( warnings[ 'was-deleted' ] !== undefined ) {
398 return $.Deferred().resolve( new OO.ui.Error(
399 $( '<p>' ).msg( 'filewasdeleted', 'File:' + warnings[ 'was-deleted' ] ),
400 { recoverable: false }
402 } else if ( warnings.badfilename !== undefined ) {
403 // Change the name if the current name isn't acceptable
404 // TODO This might not really be the best place to do this
405 this.setFilename( warnings.badfilename );
406 return $.Deferred().resolve( new OO.ui.Error(
407 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
410 return $.Deferred().resolve( new OO.ui.Error(
411 // Let's get all the help we can if we can't pin point the error
412 $( '<p>' ).msg( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ),
413 { recoverable: false }
422 * Renders and returns the upload form and sets the
423 * {@link #uploadForm uploadForm} property.
427 * @return {OO.ui.FormLayout}
429 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
433 this.selectFileWidget = this.getFileWidget();
434 fieldset = new OO.ui.FieldsetLayout();
435 fieldset.addItems( [ this.selectFileWidget ] );
436 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
438 // Validation (if the SFW is for a stashed file, this never fires)
439 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
441 this.selectFileWidget.on( 'change', function () {
442 layout.updateFilePreview();
445 return this.uploadForm;
449 * Gets the widget for displaying or inputting the file to upload.
451 * @return {OO.ui.SelectFileWidget|mw.widgets.StashedFileWidget}
453 mw.Upload.BookletLayout.prototype.getFileWidget = function () {
454 if ( this.filekey ) {
455 return new mw.widgets.StashedFileWidget( {
456 filekey: this.filekey
460 return new OO.ui.SelectFileWidget( {
466 * Updates the file preview on the info form when a file is added.
470 mw.Upload.BookletLayout.prototype.updateFilePreview = function () {
471 this.selectFileWidget.loadAndGetImageUrl().done( function ( url ) {
472 this.filePreview.$element.find( 'p' ).remove();
473 this.filePreview.$element.css( 'background-image', 'url(' + url + ')' );
474 this.infoForm.$element.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
475 }.bind( this ) ).fail( function () {
476 this.filePreview.$element.find( 'p' ).remove();
477 if ( this.selectFileWidget.getValue() ) {
478 this.filePreview.$element.append(
479 $( '<p>' ).text( this.selectFileWidget.getValue().name )
482 this.filePreview.$element.css( 'background-image', '' );
483 this.infoForm.$element.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
488 * Handle change events to the upload form
493 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
494 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
498 * Renders and returns the information form for collecting
499 * metadata and sets the {@link #infoForm infoForm}
503 * @return {OO.ui.FormLayout}
505 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
508 this.filePreview = new OO.ui.Widget( {
509 classes: [ 'mw-upload-bookletLayout-filePreview' ]
511 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
514 this.filePreview.$element.append( this.progressBarWidget.$element );
516 this.filenameWidget = new OO.ui.TextInputWidget( {
517 indicator: 'required',
521 this.descriptionWidget = new OO.ui.TextInputWidget( {
522 indicator: 'required',
529 fieldset = new OO.ui.FieldsetLayout( {
530 label: mw.msg( 'upload-form-label-infoform-title' )
533 new OO.ui.FieldLayout( this.filenameWidget, {
534 label: mw.msg( 'upload-form-label-infoform-name' ),
536 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
538 new OO.ui.FieldLayout( this.descriptionWidget, {
539 label: mw.msg( 'upload-form-label-infoform-description' ),
541 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
544 this.infoForm = new OO.ui.FormLayout( {
545 classes: [ 'mw-upload-bookletLayout-infoForm' ],
546 items: [ this.filePreview, fieldset ]
549 this.on( 'fileUploadProgress', function ( progress ) {
550 this.progressBarWidget.setProgress( progress * 100 );
553 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
554 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
556 return this.infoForm;
560 * Handle change events to the info form
565 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
568 this.filenameWidget.getValidity(),
569 this.descriptionWidget.getValidity()
570 ).done( function () {
571 layout.emit( 'infoValid', true );
572 } ).fail( function () {
573 layout.emit( 'infoValid', false );
578 * Renders and returns the insert form to show file usage and
579 * sets the {@link #insertForm insertForm} property.
582 * @return {OO.ui.FormLayout}
584 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
587 this.filenameUsageWidget = new OO.ui.TextInputWidget();
588 fieldset = new OO.ui.FieldsetLayout( {
589 label: mw.msg( 'upload-form-label-usage-title' )
592 new OO.ui.FieldLayout( this.filenameUsageWidget, {
593 label: mw.msg( 'upload-form-label-usage-filename' ),
597 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
599 return this.insertForm;
605 * Gets the file object from the
606 * {@link #uploadForm upload form}.
609 * @return {File|null}
611 mw.Upload.BookletLayout.prototype.getFile = function () {
612 return this.selectFileWidget.getValue();
616 * Gets the file name from the
617 * {@link #infoForm information form}.
622 mw.Upload.BookletLayout.prototype.getFilename = function () {
623 var filename = this.filenameWidget.getValue();
624 if ( this.filenameExtension ) {
625 filename += '.' + this.filenameExtension;
631 * Prefills the {@link #infoForm information form} with the given filename.
634 * @param {string} filename
636 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
637 var title = mw.Title.newFromFileName( filename );
640 this.filenameWidget.setValue( title.getNameText() );
641 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
643 // Seems to happen for files with no extension, which should fail some checks anyway...
644 this.filenameWidget.setValue( filename );
645 this.filenameExtension = null;
650 * Gets the page text from the
651 * {@link #infoForm information form}.
656 mw.Upload.BookletLayout.prototype.getText = function () {
657 return this.descriptionWidget.getValue();
663 * Sets the file object
666 * @param {File|null} file File to select
668 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
669 this.selectFileWidget.setValue( file );
673 * Sets the filekey of a file already stashed on the server
674 * as the target of this upload operation.
677 * @param {string} filekey
679 mw.Upload.BookletLayout.prototype.setFilekey = function ( filekey ) {
680 this.upload.setFilekey( this.filekey );
681 this.selectFileWidget.setValue( filekey );
683 this.onUploadFormChange();
687 * Clear the values of all fields
691 mw.Upload.BookletLayout.prototype.clear = function () {
692 this.selectFileWidget.setValue( null );
693 this.progressBarWidget.setProgress( 0 );
694 this.filenameWidget.setValue( null ).setValidityFlag( true );
695 this.descriptionWidget.setValue( null ).setValidityFlag( true );
696 this.filenameUsageWidget.setValue( null );
699 }( jQuery, mediaWiki, moment ) );