@i-novus/ui-core
Version:
Базовые UI компоненты
47 lines (46 loc) • 2.81 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { useConfigProvider } from '../core';
import { Button } from '../general/Button';
import { Icon } from '../data-display/Icon';
const DEFAULT_HEIGHT = 150;
export const FilePicker = ({ prefix, className, description, label, onChange, accept = [], disabled = false, multiple = false }) => {
const contentRef = useRef(null);
const [height, setHeight] = useState(DEFAULT_HEIGHT);
const { getPrefix } = useConfigProvider();
const prefixCls = getPrefix(prefix);
const [isDrag, setIsDrag] = useState(false);
const nativeInputRef = useRef(null);
const handleFileInputChange = useCallback((event) => {
const { files: filesList } = event.target;
if (!filesList || filesList.length === 0) {
return;
}
const files = [...filesList];
onChange(files, event);
if (nativeInputRef.current) {
nativeInputRef.current.value = '';
}
}, [onChange]);
const handleUploadButtonClick = useCallback(() => {
const { current } = nativeInputRef;
if (!current) {
return;
}
current.click();
}, [nativeInputRef]);
const handleDragOver = useCallback(() => {
setIsDrag(true);
}, []);
const handleDragLeave = useCallback(() => {
setIsDrag(false);
}, []);
useLayoutEffect(() => {
if (contentRef?.current) {
setHeight(contentRef.current.getBoundingClientRect()?.height || DEFAULT_HEIGHT);
}
}, [contentRef]);
return (_jsxs("div", { className: classNames(`${prefixCls}-file-picker`, isDrag && `${prefixCls}-file-picker__drag`, disabled && `${prefixCls}-file-picker__disabled`, className), style: { height }, children: [_jsx("input", { ref: nativeInputRef, type: "file", multiple: multiple, accept: accept.join(','), disabled: disabled, onDragOver: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDragLeave, onChange: handleFileInputChange }), _jsx("svg", { width: "100%", height: "100%", children: _jsx("rect", { width: "100%", height: "100%", x: "2", y: "2", rx: "8", ry: "8" }) }), _jsxs("div", { ref: contentRef, className: `${prefixCls}-file-picker_drop-area`, children: [_jsx("span", { className: `${prefixCls}-file-picker_description`, children: description || 'Перетащите файлы или выберите на компьютере' }), _jsxs(Button, { className: `${prefixCls}-file-picker_button`, disabled: disabled, variant: "link", onClick: handleUploadButtonClick, children: [_jsx(Icon, { icon: "common-add" }), label || 'Выбрать файл'] })] })] }));
};
FilePicker.displayName = 'FilePicker';