gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

file.jsx (2106B)


      1 /*
      2 	GoToSocial
      3 	Copyright (C) GoToSocial Authors admin@gotosocial.org
      4 	SPDX-License-Identifier: AGPL-3.0-or-later
      5 
      6 	This program is free software: you can redistribute it and/or modify
      7 	it under the terms of the GNU Affero General Public License as published by
      8 	the Free Software Foundation, either version 3 of the License, or
      9 	(at your option) any later version.
     10 
     11 	This program is distributed in the hope that it will be useful,
     12 	but WITHOUT ANY WARRANTY; without even the implied warranty of
     13 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     14 	GNU Affero General Public License for more details.
     15 
     16 	You should have received a copy of the GNU Affero General Public License
     17 	along with this program.  If not, see <http://www.gnu.org/licenses/>.
     18 */
     19 
     20 "use strict";
     21 
     22 const React = require("react");
     23 const prettierBytes = require("prettier-bytes");
     24 
     25 module.exports = function useFileInput({ name, _Name }, {
     26 	withPreview,
     27 	maxSize,
     28 	initialInfo = "no file selected"
     29 } = {}) {
     30 	const [file, setFile] = React.useState();
     31 	const [imageURL, setImageURL] = React.useState();
     32 	const [info, setInfo] = React.useState();
     33 
     34 	function onChange(e) {
     35 		let file = e.target.files[0];
     36 		setFile(file);
     37 
     38 		URL.revokeObjectURL(imageURL);
     39 
     40 		if (file != undefined) {
     41 			if (withPreview) {
     42 				setImageURL(URL.createObjectURL(file));
     43 			}
     44 
     45 			let size = prettierBytes(file.size);
     46 			if (maxSize && file.size > maxSize) {
     47 				size = <span className="error-text">{size}</span>;
     48 			}
     49 
     50 			setInfo(<>
     51 				{file.name} ({size})
     52 			</>);
     53 		} else {
     54 			setInfo();
     55 		}
     56 	}
     57 
     58 	function reset() {
     59 		URL.revokeObjectURL(imageURL);
     60 		setImageURL();
     61 		setFile();
     62 		setInfo();
     63 	}
     64 
     65 	const infoComponent = (
     66 		<span className="form-info">
     67 			{info
     68 				? info
     69 				: initialInfo
     70 			}
     71 		</span>
     72 	);
     73 
     74 	// Array / Object hybrid, for easier access in different contexts
     75 	return Object.assign([
     76 		onChange,
     77 		reset,
     78 		{
     79 			[name]: file,
     80 			[`${name}URL`]: imageURL,
     81 			[`${name}Info`]: infoComponent,
     82 		}
     83 	], {
     84 		onChange,
     85 		reset,
     86 		name,
     87 		value: file,
     88 		previewValue: imageURL,
     89 		hasChanged: () => file != undefined,
     90 		infoComponent
     91 	});
     92 };