Files
sencho/frontend/src/lib/utils.ts
T
Anso 60092dd462 feat: live-refresh stack detail container and health state (#1712)
* feat: live-refresh stack detail container and health state

Keep the open stack's container cards in sync with Docker via state-invalidate events and a visibility-aware poll, without reloading compose, env, or logs.

* fix: remove unused _ms parameter from visibilityInterval mock

Fixes the @typescript-eslint/no-unused-vars ESLint error in CI lint job.

* fix: stop stack detail live-refresh when leaving the editor

Gate poll and invalidate handling on editor visibility, refresh the
current selection after a mid-flight stack switch, and skip starting
visibilityInterval when the tab is already hidden.

* fix: avoid return in finally for stack detail live-refresh

Satisfy no-unsafe-finally by gating the trailing refresh with a positive
condition instead of early returns inside the finally block.
2026-07-28 09:24:18 -04:00

44 lines
1.9 KiB
TypeScript

import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatBytes(bytes: number, decimals = 2) {
if (!+bytes) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}
export function formatCount(n: number, unit: string): string {
if (n === 0) return 'None';
return `${n} ${unit}${n === 1 ? '' : 's'}`;
}
/** Format a Unix timestamp (seconds) as a human-readable relative string, e.g. "42s ago", "5m ago". */
export function formatRelativeTime(timestampSeconds: number): string {
const seconds = Math.floor(Date.now() / 1000 - timestampSeconds);
if (seconds < 60) return `${seconds}s ago`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
export function visibilityInterval(fn: () => void, ms: number): () => void {
let interval: ReturnType<typeof setInterval> | null = null;
const start = () => { if (interval) return; interval = setInterval(fn, ms); };
const stop = () => { if (interval) { clearInterval(interval); interval = null; } };
const onVisChange = () => { if (document.hidden) { stop(); } else { fn(); start(); } };
document.addEventListener('visibilitychange', onVisChange);
// Do not start a timer when the tab is already hidden (e.g. deep-link opened
// in a background tab). Resume via visibilitychange when the tab is shown.
if (!document.hidden) start();
return () => { stop(); document.removeEventListener('visibilitychange', onVisChange); };
}