diff --git a/web/src/components/Item.tsx b/web/src/components/Item.tsx index d0062d8..f025224 100644 --- a/web/src/components/Item.tsx +++ b/web/src/components/Item.tsx @@ -12,6 +12,7 @@ import { useDownloadTorrentMutation } from "../api/useDownloadTorrentMutation"; import { useDeleteItemMutation } from "../api/useDeleteItemMutation"; import { useQueryClient } from "@tanstack/react-query"; import dayjs from "dayjs"; +import { humanFileSize } from "../utils/humanFileSize"; export type ItemProps = { item: ItemDetails; @@ -105,6 +106,7 @@ export const Item = ({ item }: ItemProps) => { > + {humanFileSize(torrent.size)} )) diff --git a/web/src/utils/humanFileSize.ts b/web/src/utils/humanFileSize.ts new file mode 100644 index 0000000..8e5272f --- /dev/null +++ b/web/src/utils/humanFileSize.ts @@ -0,0 +1,23 @@ +export const humanFileSize = (bytes: number, si = false, dp = 1): string => { + const thresh = si ? 1000 : 1024; + + if (Math.abs(bytes) < thresh) { + return bytes + " B"; + } + + const units = si + ? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] + : ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; + let u = -1; + const r = 10 ** dp; + + do { + bytes /= thresh; + ++u; + } while ( + Math.round(Math.abs(bytes) * r) / r >= thresh && + u < units.length - 1 + ); + + return bytes.toFixed(dp) + " " + units[u]; +};