Files
relicario/extension/src/shared/relative-time.ts
2026-05-30 13:00:58 -04:00

28 lines
1.4 KiB
TypeScript

/// 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);
}