Skip to content

Commit

Permalink
feat: add human friendly file size formatting (#146)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel N <[email protected]>
  • Loading branch information
2color and 2color authored Oct 10, 2024
1 parent 774a4c8 commit f9b0f74
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/components/file/file.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { CircularProgressbar } from 'react-circular-progressbar'
import { CopyToClipboard } from 'react-copy-to-clipboard'
import { useTranslation } from 'react-i18next'
import { useHelia } from '../../hooks/use-helia.js'
import { formatBytes } from '../../lib/size.js'
import IconDownload from '../../media/icons/download.svg'
import IconView from '../../media/icons/view.svg'
import { type FileState } from '../../providers/files-provider.jsx'
Expand Down Expand Up @@ -144,7 +145,7 @@ export const File = ({ file, isDownload }: { file: FileState, isDownload?: boole
<FileIcon className="flex-shrink-0" name={name} error={error} />
</div>
<span className={fileNameClass}>{name}</span>
<span className={fileSizeClass}>{size != null ? `(~${size})` : ''}</span>
<span className={fileSizeClass}>{size != null ? `(~${formatBytes(size)})` : ''}</span>
</div>
<div className='flex items-center'>
<span className='ml-auto'>{ renderFileStatus() }</span>
Expand Down
13 changes: 13 additions & 0 deletions src/lib/size.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function formatBytes (bytes: number, decimals = 0): string {
if (bytes === 0 || isNaN(bytes)) {
return '0 Bytes'
}

const k = 1024 // constant for the base of the exponentiation
const dm = decimals < 0 ? 0 : decimals // determines the number of decimal places to display
const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'] // array of size units

const i = Math.floor(Math.log(bytes) / Math.log(k)) // calculates the appropriate size unit index

return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}` // formats the size with the appropriate unit
}

0 comments on commit f9b0f74

Please sign in to comment.