UNPKG

@carbon/react

Version:

React components for the Carbon Design System

328 lines (323 loc) 10.6 kB
/** * Copyright IBM Corp. 2016, 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import { extends as _extends } from '../../_virtual/_rollupPluginBabelHelpers.js'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React, { useState, useCallback, useImperativeHandle } from 'react'; import Filename from './Filename.js'; import FileUploaderButton from './FileUploaderButton.js'; import { ButtonKinds } from '../Button/Button.js'; import { Enter, Space } from '../../internal/keyboard/keys.js'; import { matches } from '../../internal/keyboard/match.js'; import { usePrefix } from '../../internal/usePrefix.js'; import '../Text/index.js'; import { useId } from '../../internal/useId.js'; import { useFeatureFlag } from '../FeatureFlags/index.js'; import { Text } from '../Text/Text.js'; const FileUploader = /*#__PURE__*/React.forwardRef(({ accept, buttonKind, buttonLabel, className, disabled, filenameStatus, iconDescription, labelDescription, labelTitle, multiple, name, onChange, onClick, onDelete, size, ...other }, ref) => { const fileUploaderInstanceId = useId('file-uploader'); const prefix = usePrefix(); const enhancedFileUploaderEnabled = useFeatureFlag('enable-enhanced-file-uploader'); const [fileItems, setFileItems] = useState([]); const [legacyFileNames, setLegacyFileNames] = useState([]); const [fileObjects, setFileObjects] = useState(new Map()); const nodes = []; const createFileItem = file => ({ name: file.name, uuid: `${fileUploaderInstanceId}-${Date.now()}-${Array.from(crypto.getRandomValues(new Uint8Array(8))).map(b => b.toString(36)).join('')}`, file }); const handleChange = useCallback(evt => { evt.stopPropagation(); const newFiles = Array.from(evt.target.files); if (enhancedFileUploaderEnabled) { const newFileItems = newFiles.map(createFileItem); let updatedFileItems; if (multiple) { const existingNames = new Set(fileItems.map(item => item.name)); const uniqueNewItems = newFileItems.filter(item => !existingNames.has(item.name)); updatedFileItems = [...fileItems, ...uniqueNewItems]; } else { updatedFileItems = newFileItems; } setFileItems(updatedFileItems); if (onChange) { const allFiles = updatedFileItems.map(item => item.file); const enhancedEvent = { ...evt, target: { ...evt.target, files: Object.assign(allFiles, { item: index => allFiles[index] || null }), addedFiles: newFileItems, currentFiles: updatedFileItems, action: 'add' } }; onChange(enhancedEvent); } } else { const filenames = newFiles.map(file => file.name); const updatedFileNames = multiple ? [...new Set([...legacyFileNames, ...filenames])] : filenames; setLegacyFileNames(updatedFileNames); setFileObjects(prevMap => { const newMap = multiple ? new Map(prevMap) : new Map(); newFiles.forEach(file => { newMap.set(file.name, file); }); return newMap; }); if (onChange) { onChange(evt); } } }, [enhancedFileUploaderEnabled, fileItems, legacyFileNames, multiple, onChange]); const handleClick = useCallback((evt, { index, filenameStatus }) => { if (filenameStatus === 'edit') { evt.stopPropagation(); if (enhancedFileUploaderEnabled) { const deletedItem = fileItems[index]; if (!deletedItem) return; const remainingItems = fileItems.filter((_, i) => i !== index); setFileItems(remainingItems); const remainingFiles = remainingItems.map(item => item.file); const enhancedEvent = { ...evt, target: { ...evt.target, files: Object.assign(remainingFiles, { item: index => remainingFiles[index] || null }), deletedFile: deletedItem, deletedFileName: deletedItem.name, remainingFiles: remainingItems, currentFiles: remainingItems, action: 'remove' } }; if (onDelete) { onDelete(enhancedEvent); } if (onChange) { onChange(enhancedEvent); } } else { const deletedFileName = legacyFileNames[index]; const filteredArray = legacyFileNames.filter(filename => filename !== deletedFileName); setLegacyFileNames(filteredArray); // Update File objects setFileObjects(prevMap => { const newMap = new Map(prevMap); if (deletedFileName) { newMap.delete(deletedFileName); } return newMap; }); if (onDelete) { onDelete(evt); } } if (onClick) { onClick(evt); } uploaderButton.current?.focus?.(); } }, [enhancedFileUploaderEnabled, fileItems, legacyFileNames, onDelete, onChange, onClick]); useImperativeHandle(ref, () => ({ clearFiles() { if (enhancedFileUploaderEnabled) { const previousItems = [...fileItems]; setFileItems([]); if (onChange && previousItems.length > 0) { const enhancedEvent = { target: { files: Object.assign([], { item: () => null }), clearedFiles: previousItems, currentFiles: [], action: 'clear' }, preventDefault: () => {}, stopPropagation: () => {} }; onChange(enhancedEvent); } } else { setLegacyFileNames([]); setFileObjects(new Map()); } }, ...(enhancedFileUploaderEnabled && { getCurrentFiles() { return [...fileItems]; } }) }), [enhancedFileUploaderEnabled, fileItems, onChange]); const uploaderButton = /*#__PURE__*/React.createRef(); const classes = cx({ [`${prefix}--form-item`]: true, [className]: className }); const getHelperLabelClasses = baseClass => cx(baseClass, { [`${prefix}--label-description--disabled`]: disabled }); const selectedFileClasses = cx(`${prefix}--file__selected-file`, { [`${prefix}--file__selected-file--md`]: size === 'field' || size === 'md', [`${prefix}--file__selected-file--sm`]: size === 'small' || size === 'sm' }); const displayFiles = enhancedFileUploaderEnabled ? fileItems.map((item, index) => ({ name: item.name, key: item.uuid, index })) : legacyFileNames.map((name, index) => ({ name, key: index, index })); return /*#__PURE__*/React.createElement("div", _extends({ className: classes }, other), !labelTitle ? null : /*#__PURE__*/React.createElement(Text, { as: "h3", className: getHelperLabelClasses(`${prefix}--file--label`) }, labelTitle), /*#__PURE__*/React.createElement(Text, { as: "p", className: getHelperLabelClasses(`${prefix}--label-description`), id: fileUploaderInstanceId }, labelDescription), /*#__PURE__*/React.createElement(FileUploaderButton, { innerRef: uploaderButton, disabled: disabled, labelText: buttonLabel, multiple: multiple, buttonKind: buttonKind, onChange: handleChange, disableLabelChanges: true, accept: accept, name: name, size: size, "aria-describedby": fileUploaderInstanceId }), /*#__PURE__*/React.createElement("div", { className: `${prefix}--file-container` }, displayFiles.length === 0 ? null : displayFiles.map(file => /*#__PURE__*/React.createElement("span", _extends({ key: file.key, className: selectedFileClasses, ref: node => { nodes[file.index] = node; } }, other), /*#__PURE__*/React.createElement(Text, { as: "p", className: `${prefix}--file-filename`, id: enhancedFileUploaderEnabled ? `${fileUploaderInstanceId}-file-${fileItems[file.index]?.uuid || file.index}` : `${fileUploaderInstanceId}-file-${file.index}` }, file.name), /*#__PURE__*/React.createElement("span", { className: `${prefix}--file__state-container` }, /*#__PURE__*/React.createElement(Filename, { name: file.name, iconDescription: iconDescription, status: filenameStatus, onKeyDown: evt => { if (matches(evt, [Enter, Space])) { handleClick(evt, { index: file.index, filenameStatus }); } }, onClick: evt => handleClick(evt, { index: file.index, filenameStatus }) })))))); }); FileUploader.propTypes = { /** * Specify the types of files that this input should be able to receive */ accept: PropTypes.arrayOf(PropTypes.string), /** * Specify the type of the `<FileUploaderButton>` */ buttonKind: PropTypes.oneOf(ButtonKinds), /** * Provide the label text to be read by screen readers when interacting with * the `<FileUploaderButton>` */ buttonLabel: PropTypes.string, /** * Provide a custom className to be applied to the container node */ className: PropTypes.string, /** * Specify whether file input is disabled */ disabled: PropTypes.bool, /** * Specify the status of the File Upload */ filenameStatus: PropTypes.oneOf(['edit', 'complete', 'uploading']).isRequired, /** * Provide a description for the complete/close icon that can be read by screen readers */ iconDescription: PropTypes.string, /** * Specify the description text of this `<FileUploader>` */ labelDescription: PropTypes.string, /** * Specify the title text of this `<FileUploader>` */ labelTitle: PropTypes.string, /** * Specify if the component should accept multiple files to upload */ multiple: PropTypes.bool, /** * Provide a name for the underlying `<input>` node */ name: PropTypes.string, /** * Provide an optional `onChange` hook that is called each time the input is * changed */ onChange: PropTypes.func, /** * Provide an optional `onClick` hook that is called each time the * FileUploader is clicked */ onClick: PropTypes.func, /** * Provide an optional `onDelete` hook that is called when an uploaded item * is removed */ onDelete: PropTypes.func, /** * Specify the size of the FileUploaderButton, from a list of available * sizes. */ size: PropTypes.oneOf(['sm', 'small', 'md', 'field', 'lg']) }; export { FileUploader as default };