'use client'; import classnames from 'classnames'; import React from 'react'; import MdIconButton from '../iconButton/MdIconButton'; import MdIconDelete from '../icons-material/MdIconDelete'; import MdIconDescription from '../icons-material/MdIconDescription'; import MdIconDownload from '../icons-material/MdIconDownload'; import MdIconEdit from '../icons-material/MdIconEdit'; import MdIconPrint from '../icons-material/MdIconPrint'; interface FileType { name: string; id?: string; url?: string; size?: number; type?: string; } interface Labels { delete?: string; download?: string; edit?: string; print?: string; } export interface MdFileListProps { files?: File[] | FileType[]; hideDownload?: boolean; hidePrint?: boolean; allowDelete?: boolean; allowEdit?: boolean; hideIcons?: boolean; printableFileTypes?: string[]; onRemoveFile?(_file: File | FileType): void; onDownloadFile?(_file: File | FileType): void; onEditFile?(_file: File | FileType): void; onPrintFile?(_file: File | FileType): void; labels?: Labels; } const formatBytes = (bytes: number, decimals = 2): string => { if (typeof bytes !== 'number') return 'n/a'; if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; }; export const MdFileList: React.FunctionComponent = ({ files, hideDownload = false, hidePrint = true, allowDelete = false, allowEdit = true, hideIcons = false, printableFileTypes = ['pdf', 'docx'], onRemoveFile, onDownloadFile, onEditFile, onPrintFile, labels = {}, }: MdFileListProps) => { const defaultLabels: Required = { delete: 'Slett fil', download: 'Last ned fil', edit: 'Rediger fil', print: 'Skriv ut fil', }; const mergedLabels: Required = { ...defaultLabels, ...labels }; const outerClass = classnames('md-filelist'); const fileClass = classnames('md-filelist__file'); return (
{files && files.length > 0 && files.map((file: FileType | File, index: number) => { const fileEnding = file.name.split('.').pop(); return (
{!hideIcons && (
)}
{file.name}
{file.size &&
{formatBytes(file.size)}
}
{!hideDownload && onDownloadFile && 'url' in file && ( { onDownloadFile(file); }} > )} {allowDelete && onRemoveFile && ( { onRemoveFile(file); }} > )} {allowEdit && onEditFile && ( { onEditFile(file); }} > )} {!hidePrint && onPrintFile && fileEnding && printableFileTypes.includes(fileEnding) && ( { onPrintFile(file); }} > )}
); })}
); }; export default MdFileList;