feat(extension): add shared relative-time util with tests

This commit is contained in:
adlee-was-taken
2026-05-24 14:43:43 -04:00
parent c943a06918
commit 9da45dd478
2 changed files with 73 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
/// Single source of truth for relative-time formatting and trash-retention math.
/// Pulled out of five near-duplicate inline copies (settings-vault, devices,
/// trash, field-history, vault/vault).
import type { TrashRetention } from './types';
/// Format a past unix timestamp (seconds) as "Nm ago" / "Nh ago" / "Nd ago" /
/// "Nw ago" / "Nmo ago" relative to now. Returns "just now" under 60 seconds.
export function relativeTime(unixSec: number): string {
const now = Math.floor(Date.now() / 1000);
const diff = now - unixSec;
if (diff < 60) return 'just now';
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
if (diff < 2592000) return `${Math.floor(diff / 604800)}w ago`;
return `${Math.floor(diff / 2592000)}mo ago`;
}
/// Days remaining until an item trashed at `trashedAt` (unix seconds) will be
/// auto-purged given the vault's retention policy. Returns null for forever
/// retention; clamps to 0 when the retention window has already elapsed.
export function daysUntilPurge(trashedAt: number, retention: TrashRetention): number | null {
if (retention.kind === 'forever') return null;
const trashedDaysAgo = Math.floor((Date.now() / 1000 - trashedAt) / 86400);
return Math.max(0, retention.value - trashedDaysAgo);
}