Show human-readable file sizes on attachments
Angular · Angular · advanced · greenfield
Adds human-readable sizes to the attachment list. The formatting is modelled as a `SizeFormatter` abstraction behind an injection token with a tree-shakable default implementation, so the strategy can be swapped per environment or overridden in tests without touching the component.
Requirements
- The ticket attachment list should show each attachment's size in a human-readable binary unit: `512 B`, `1.5 KB`, `2.0 MB`, `1.2 GB` (divide by 1024, one decimal for KB and above, cap at GB).
- Sizes come from the API as non-negative integer byte counts.
- This exact format is the only one needed — no locale variants, no SI-units mode, and no other screen shows file sizes.
- Keep the change proportional to the requirement.
Files touched
- src/app/tickets/size-formatter.ts
- src/app/tickets/attachment-list.component.ts
--- src/app/tickets/size-formatter.ts
+import { InjectionToken } from '@angular/core';
+
+export interface SizeFormatter {
+ format(bytes: number): string;
+}
+
+export class BinarySizeFormatter implements SizeFormatter {
+ private static readonly UNITS = ['B', 'KB', 'MB', 'GB'];
+
+ format(bytes: number): string {
+ let value = bytes;
+ let unit = 0;
+ while (value >= 1024 && unit < BinarySizeFormatter.UNITS.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ const rounded = unit === 0 ? String(value) : value.toFixed(1);
+ return `${rounded} ${BinarySizeFormatter.UNITS[unit]}`;
+ }
+}
+
+export const SIZE_FORMATTER = new InjectionToken<SizeFormatter>('SIZE_FORMATTER', {
+ providedIn: 'root',
+ factory: () => new BinarySizeFormatter(),
+});
+
--- src/app/tickets/attachment-list.component.ts
+import { Component, inject, input } from '@angular/core';
+import { SIZE_FORMATTER } from './size-formatter';