all files / src/src/widgets/ SelectFileInputWidget.js

63.29% Statements 50/79
32.5% Branches 13/40
50% Functions 6/12
63.29% Lines 50/79
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277                                                    720×   720×     720×                     720×           720×             720×   720×     720×     720×           720× 720× 76×   644×   720×     720× 720×     720×                     720×   720×   720×                   720× 76×   720× 72×   720×   720×       720×                                     720×           720×             720×   720×                                                             720×                   720×                                               720×                                                                             720×   720× 720×   720×    
/**
 * SelectFileInputWidgets allow for selecting files, using <input type="file">. These
 * widgets can be configured with {@link OO.ui.mixin.IconElement icons}, {@link
 * OO.ui.mixin.IndicatorElement indicators} and {@link OO.ui.mixin.TitledElement titles}.
 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
 *
 * SelectFileInputWidgets must be used in HTML forms, as getValue only returns the filename.
 *
 *     @example
 *     // A file select input widget.
 *     var selectFile = new OO.ui.SelectFileInputWidget();
 *     $( document.body ).append( selectFile.$element );
 *
 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets
 *
 * @class
 * @extends OO.ui.InputWidget
 *
 * @constructor
 * @param {Object} [config] Configuration options
 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
 * @cfg {boolean} [multiple=false] Allow multiple files to be selected.
 * @cfg {string} [placeholder] Text to display when no file is selected.
 * @cfg {Object} [button] Config to pass to select file button.
 * @cfg {string} [icon] Icon to show next to file info
 */
OO.ui.SelectFileInputWidget = function OoUiSelectFileInputWidget( config ) {
	var widget = this;
 
	config = config || {};
 
	// Construct buttons before parent method is called (calling setDisabled)
	this.selectButton = new OO.ui.ButtonWidget( $.extend( {
		$element: $( '<label>' ),
		classes: [ 'oo-ui-selectFileInputWidget-selectButton' ],
		label: OO.ui.msg(
			config.multiple ?
				'ooui-selectfile-button-select-multiple' :
				'ooui-selectfile-button-select'
		)
	}, config.button ) );
 
	// Configuration initialization
	config = $.extend( {
		accept: null,
		placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
		$tabIndexed: this.selectButton.$tabIndexed
	}, config );
 
	this.info = new OO.ui.SearchInputWidget( {
		classes: [ 'oo-ui-selectFileInputWidget-info' ],
		placeholder: config.placeholder,
		// Pass an empty collection so that .focus() always does nothing
		$tabIndexed: $( [] )
	} ).setIcon( config.icon );
	// Set tabindex manually on $input as $tabIndexed has been overridden
	this.info.$input.attr( 'tabindex', -1 );
	// This indicator serves as the only way to clear the file, so it must be keyboard-accessible
	this.info.$indicator.attr( 'tabindex', 0 );
 
	// Parent constructor
	OO.ui.SelectFileInputWidget.super.call( this, config );
 
	// Mixin constructors
	OO.ui.mixin.RequiredElement.call( this, $.extend( {}, {
		// TODO: Display the required indicator somewhere
		indicatorElement: null
	}, config ) );
 
	// Properties
	this.currentFiles = this.filterFiles( this.$input[ 0 ].files || [] );
	if ( Array.isArray( config.accept ) ) {
		this.accept = config.accept;
	} else {
		this.accept = null;
	}
	this.multiple = !!config.multiple;
 
	// Events
	this.info.connect( this, { change: 'onInfoChange' } );
	this.selectButton.$button.on( {
		keypress: this.onKeyPress.bind( this )
	} );
	this.$input.on( {
		change: this.onFileSelected.bind( this ),
		// Support: IE11
		// In IE 11, focussing a file input (by clicking on it) displays a text cursor and scrolls
		// the cursor into view (in this case, it scrolls the button, which has 'overflow: hidden').
		// Since this messes with our custom styling (the file input has large dimensions and this
		// causes the label to scroll out of view), scroll the button back to top. (T192131)
		focus: function () {
			widget.$input.parent().prop( 'scrollTop', 0 );
		}
	} );
	this.connect( this, { change: 'updateUI' } );
 
	this.fieldLayout = new OO.ui.ActionFieldLayout( this.info, this.selectButton, { align: 'top' } );
 
	this.$input
		.attr( {
			type: 'file',
			// this.selectButton is tabindexed
			tabindex: -1,
			// Infused input may have previously by
			// TabIndexed, so remove aria-disabled attr.
			'aria-disabled': null
		} );
 
	if ( this.accept ) {
		this.$input.attr( 'accept', this.accept.join( ', ' ) );
	}
	if ( this.multiple ) {
		this.$input.attr( 'multiple', '' );
	}
	this.selectButton.$button.append( this.$input );
 
	this.$element
		.addClass( 'oo-ui-selectFileInputWidget' )
		.append( this.fieldLayout.$element );
 
	this.updateUI();
};
 
/* Setup */
 
OO.inheritClass( OO.ui.SelectFileInputWidget, OO.ui.InputWidget );
OO.mixinClass( OO.ui.SelectFileInputWidget, OO.ui.mixin.RequiredElement );
 
/* Static Properties */
 
// Set empty title so that browser default tooltips like "No file chosen" don't appear.
// On SelectFileWidget this tooltip will often be incorrect, so create a consistent
// experience on SelectFileInputWidget.
OO.ui.SelectFileInputWidget.static.title = '';
 
/* Methods */
 
/**
 * Get the filename of the currently selected file.
 *
 * @return {string} Filename
 */
OO.ui.SelectFileInputWidget.prototype.getFilename = function () {
	Iif ( this.currentFiles.length ) {
		return this.currentFiles.map( function ( file ) {
			return file.name;
		} ).join( ', ' );
	} else {
		// Try to strip leading fakepath.
		return this.getValue().split( '\\' ).pop();
	}
};
 
/**
 * @inheritdoc
 */
OO.ui.SelectFileInputWidget.prototype.setValue = function ( value ) {
	Eif ( value === undefined ) {
		// Called during init, don't replace value if just infusing.
		return this;
	}
	if ( value ) {
		// We need to update this.value, but without trying to modify
		// the DOM value, which would throw an exception.
		if ( this.value !== value ) {
			this.value = value;
			this.emit( 'change', this.value );
		}
		return this;
	} else {
		this.currentFiles = [];
		// Parent method
		return OO.ui.SelectFileInputWidget.super.prototype.setValue.call( this, '' );
	}
};
 
/**
 * Handle file selection from the input.
 *
 * @protected
 * @param {jQuery.Event} e
 */
OO.ui.SelectFileInputWidget.prototype.onFileSelected = function ( e ) {
	this.currentFiles = this.filterFiles( e.target.files || [] );
};
 
/**
 * Update the user interface when a file is selected or unselected.
 *
 * @protected
 */
OO.ui.SelectFileInputWidget.prototype.updateUI = function () {
	this.info.setValue( this.getFilename() );
};
 
/**
 * Determine if we should accept this file.
 *
 * @private
 * @param {FileList|File[]} files Files to filter
 * @return {File[]} Filter files
 */
OO.ui.SelectFileInputWidget.prototype.filterFiles = function ( files ) {
	var accept = this.accept;
 
	function mimeAllowed( file ) {
		var i, mimeTest,
			mimeType = file.type;
 
		if ( !accept || !mimeType ) {
			return true;
		}
 
		for ( i = 0; i < accept.length; i++ ) {
			mimeTest = accept[ i ];
			if ( mimeTest === mimeType ) {
				return true;
			} else if ( mimeTest.substr( -2 ) === '/*' ) {
				mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
				if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
					return true;
				}
			}
		}
		return false;
	}
 
	return Array.prototype.filter.call( files, mimeAllowed );
};
 
/**
 * Handle info input change events
 *
 * The info widget can only be changed by the user
 * with the clear button.
 *
 * @private
 * @param {string} value
 */
OO.ui.SelectFileInputWidget.prototype.onInfoChange = function ( value ) {
	if ( value === '' ) {
		this.setValue( null );
	}
};
 
/**
 * Handle key press events.
 *
 * @private
 * @param {jQuery.Event} e Key press event
 * @return {undefined|boolean} False to prevent default if event is handled
 */
OO.ui.SelectFileInputWidget.prototype.onKeyPress = function ( e ) {
	if ( !this.isDisabled() && this.$input &&
		( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
	) {
		// Emit a click to open the file selector.
		this.$input.trigger( 'click' );
		// Taking focus from the selectButton means keyUp isn't fired, so fire it manually.
		this.selectButton.onDocumentKeyUp( e );
		return false;
	}
};
 
/**
 * @inheritdoc
 */
OO.ui.SelectFileInputWidget.prototype.setDisabled = function ( disabled ) {
	// Parent method
	OO.ui.SelectFileInputWidget.super.prototype.setDisabled.call( this, disabled );
 
	this.selectButton.setDisabled( disabled );
	this.info.setDisabled( disabled );
 
	return this;
};