import { i18n } from "@lingui/core" import { plural, t } from "@lingui/core/macro" import { type ClassValue, clsx } from "clsx" import { listenKeys } from "nanostores" import { timeDay, timeHour, timeMinute } from "d3-time" import { useEffect, useState } from "react" import { twMerge } from "tailwind-merge" import { toast } from "@/components/ui/use-toast" import type { ChartTimeData, FingerprintRecord, SemVer, SystemRecord } from "@/types" import { HourFormat, Unit } from "./enums" import { $copyContent, $userSettings } from "./stores" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } /** Adds event listener to node and returns function that removes the listener */ export function listen(node: Node, event: string, handler: (event: T) => void) { node.addEventListener(event, handler as EventListener) return () => node.removeEventListener(event, handler as EventListener) } export async function copyToClipboard(content: string) { const duration = 1500 try { await navigator.clipboard.writeText(content) toast({ duration, description: t`Copied to clipboard`, }) } catch (_e) { $copyContent.set(content) } } // Create formatters directly without intermediate containers const createHourWithMinutesFormatter = (hour12?: boolean) => new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "numeric", hour12, }) const createShortDateFormatter = (hour12?: boolean) => new Intl.DateTimeFormat(undefined, { day: "numeric", month: "short", hour: "numeric", minute: "numeric", hour12, }) const createHourWithSecondsFormatter = (hour12?: boolean) => new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "numeric", second: "numeric", hour12, }) // Initialize formatters with default values let hourWithMinutesFormatter = createHourWithMinutesFormatter() let shortDateFormatter = createShortDateFormatter() let hourWithSecondsFormatter = createHourWithSecondsFormatter() export const currentHour12 = () => shortDateFormatter.resolvedOptions().hour12 export const hourWithMinutes = (timestamp: string) => { return hourWithMinutesFormatter.format(new Date(timestamp)) } export const formatShortDate = (timestamp: string) => { return shortDateFormatter.format(new Date(timestamp)) } export const hourWithSeconds = (timestamp: string | number) => { return hourWithSecondsFormatter.format(new Date(timestamp)) } // Update the time formatters if user changes hourFormat listenKeys($userSettings, ["hourFormat"], ({ hourFormat }) => { if (!hourFormat) return const newHour12 = hourFormat === HourFormat["12h"] if (currentHour12() !== newHour12) { hourWithMinutesFormatter = createHourWithMinutesFormatter(newHour12) shortDateFormatter = createShortDateFormatter(newHour12) hourWithSecondsFormatter = createHourWithSecondsFormatter(newHour12) } }) const dayFormatter = new Intl.DateTimeFormat(undefined, { day: "numeric", month: "short", }) export const formatDay = (timestamp: string) => { return dayFormatter.format(new Date(timestamp)) } export const updateFavicon = (() => { let prevDownCount = 0 return (downCount = 0) => { if (downCount === prevDownCount) { return } prevDownCount = downCount const svg = ` ${downCount > 0 && ` ${downCount} ` } ` const blob = new Blob([svg], { type: "image/svg+xml" }) const url = URL.createObjectURL(blob) ; (document.querySelector("link[rel='icon']") as HTMLLinkElement).href = url } })() export const chartTimeData: ChartTimeData = { "1m": { type: "1m", expectedInterval: 2000, // allow a bit of latency for one second updates (#1247) label: () => formatTimeUnit(1, "minute"), format: (timestamp: string) => hourWithSeconds(timestamp), ticks: 3, getOffset: (endTime: Date) => timeMinute.offset(endTime, -1), minVersion: "0.13.0", }, "1h": { type: "1m", expectedInterval: 60_000, label: () => formatTimeUnit(1, "hour"), // ticks: 12, format: (timestamp: string) => hourWithMinutes(timestamp), getOffset: (endTime: Date) => timeHour.offset(endTime, -1), }, "12h": { type: "10m", expectedInterval: 60_000 * 10, label: () => formatTimeUnit(12, "hour"), ticks: 12, format: (timestamp: string) => hourWithMinutes(timestamp), getOffset: (endTime: Date) => timeHour.offset(endTime, -12), }, "24h": { type: "20m", expectedInterval: 60_000 * 20, label: () => formatTimeUnit(24, "hour"), format: (timestamp: string) => hourWithMinutes(timestamp), getOffset: (endTime: Date) => timeHour.offset(endTime, -24), }, "1w": { type: "120m", expectedInterval: 60_000 * 120, label: () => formatTimeUnit(1, "week"), ticks: 7, format: (timestamp: string) => formatDay(timestamp), getOffset: (endTime: Date) => timeDay.offset(endTime, -7), }, "30d": { type: "480m", expectedInterval: 60_000 * 480, label: () => formatTimeUnit(30, "day"), ticks: 30, format: (timestamp: string) => formatDay(timestamp), getOffset: (endTime: Date) => timeDay.offset(endTime, -30), }, } /** Format number to x decimal places, without trailing zeros */ export function toFixedFloat(num: number, digits: number) { return parseFloat((digits === 0 ? Math.ceil(num) : num).toFixed(digits)) } /** Locale used for number formatting: the app's selected language, not the browser's */ function numberLocale() { return i18n.locale || undefined } /** Format number using the app's selected language (e.g. decimal and grouping separators) */ export function formatNumber(num: number) { return num.toLocaleString(numberLocale(), { numberingSystem: "latn" }) } /** Format an amount of a time unit in the app's selected language (e.g. "7 days", "7 Tage") */ export function formatTimeUnit(num: number, unit: "minute" | "hour" | "day" | "week" | "month" | "year") { return new Intl.NumberFormat(numberLocale(), { style: "unit", unit, unitDisplay: "long", numberingSystem: "latn", }).format(num) } const decimalFormatters: Map = new Map() /** Format number to x decimal places, maintaining trailing zeros */ export function decimalString(num: number, digits = 2) { if (digits === 0) { return Math.ceil(num).toString() } const locale = numberLocale() const key = `${locale}:${digits}` let formatter = decimalFormatters.get(key) if (!formatter) { formatter = new Intl.NumberFormat(locale, { minimumFractionDigits: digits, maximumFractionDigits: digits, numberingSystem: "latn", }) decimalFormatters.set(key, formatter) } return formatter.format(num) } export function formatMicroseconds(microseconds: number, fixedDigits = true): string { if (!Number.isFinite(microseconds)) { return "-" } if (microseconds < 1000) { return `${microseconds}μs` } const digitFormatter = fixedDigits ? decimalString : toFixedFloat // Thresholds are where the printed value rounds up to the next unit or // digit count (999.95ms -> 1.00s, 9.995ms -> 10.0ms, 9.995s -> 10.0s) if (microseconds < 999_950) { const digits = microseconds >= 9_995 ? 1 : 2 return `${digitFormatter(microseconds / 1000, digits)}ms` } const digits = microseconds >= 9_995_000 ? 1 : 2 return `${digitFormatter(microseconds / 1_000_000, digits)}s` } /** Get value from local or session storage */ function getStorageValue(key: string, defaultValue: unknown, storageInterface: Storage = localStorage) { const saved = storageInterface?.getItem(key) return saved ? JSON.parse(saved) : defaultValue } /** Hook to sync value in local or session storage */ export function useBrowserStorage(key: string, defaultValue: T, storageInterface: Storage = localStorage) { key = `besz-${key}` const [value, setValue] = useState(() => { return getStorageValue(key, defaultValue, storageInterface) }) useEffect(() => { storageInterface?.setItem(key, JSON.stringify(value)) }, [key, value]) return [value, setValue] as const } /** Format temperature to user's preferred unit */ export function formatTemperature(celsius: number, unit?: Unit): { value: number; unit: string } { if (!unit) { unit = $userSettings.get().unitTemp || Unit.Celsius } // biome-ignore lint/suspicious/noDoubleEquals: need loose equality check due to form data being strings if (unit == Unit.Fahrenheit) { return { value: celsius * 1.8 + 32, unit: "°F", } } return { value: celsius, unit: "°C", } } /** Format bytes to user's preferred unit */ export function formatBytes( size: number, perSecond = false, unit = Unit.Bytes, isMegabytes = false ): { value: number; unit: string } { // Convert MB to bytes if isMegabytes is true if (isMegabytes) size *= 1024 * 1024 // biome-ignore lint/suspicious/noDoubleEquals: need loose equality check due to form data being strings if (unit == Unit.Bits) { const bits = size * 8 const suffix = perSecond ? "ps" : "" if (bits < 1000) return { value: bits, unit: `b${suffix}` } if (bits < 1_000_000) return { value: bits / 1_000, unit: `Kb${suffix}` } if (bits < 1_000_000_000) return { value: bits / 1_000_000, unit: `Mb${suffix}`, } if (bits < 1_000_000_000_000) return { value: bits / 1_000_000_000, unit: `Gb${suffix}`, } return { value: bits / 1_000_000_000_000, unit: `Tb${suffix}`, } } // bytes const suffix = perSecond ? "/s" : "" if (size < 100) return { value: size, unit: `B${suffix}` } if (size < 1000 * 1024) return { value: size / 1024, unit: `KB${suffix}` } if (size < 1000 * 1024 ** 2) return { value: size / 1024 ** 2, unit: `MB${suffix}`, } if (size < 1000 * 1024 ** 3) return { value: size / 1024 ** 3, unit: `GB${suffix}`, } return { value: size / 1024 ** 4, unit: `TB${suffix}`, } } export const chartMargin = { top: 12, right: 5 } /** * Retuns value of system host, truncating full path if socket. * @example * // Assuming system.host is "/var/run/beszel.sock" * const hostname = getHostDisplayValue(system) // hostname will be "beszel.sock" */ export const getHostDisplayValue = (system: SystemRecord): string => system.host.slice(system.host.lastIndexOf("/") + 1) // export function formatUptimeString(uptimeSeconds: number): string { // if (!uptimeSeconds || isNaN(uptimeSeconds)) return "" // if (uptimeSeconds < 3600) { // const minutes = Math.trunc(uptimeSeconds / 60) // return plural({ minutes }, { one: "# minute", other: "# minutes" }) // } else if (uptimeSeconds < 172800) { // const hours = Math.trunc(uptimeSeconds / 3600) // console.log(hours) // return plural({ hours }, { one: "# hour", other: "# hours" }) // } else { // const days = Math.trunc(uptimeSeconds / 86400) // return plural({ days }, { one: "# day", other: "# days" }) // } // } /** Generate a random token for the agent */ export const generateToken = () => { try { return crypto?.randomUUID() } catch (_e) { return Array.from({ length: 2 }, () => (performance.now() * Math.random()).toString(16).replace(".", "-")).join("-") } } /** Get the hub URL from the global BESZEL object */ export const getHubURL = () => globalThis.BESZEL?.HUB_URL || window.location.origin /** Map of system IDs to their corresponding tokens (used to avoid fetching in add-system dialog) */ export const tokenMap = new Map() /** Calculate duration between two dates and format as human-readable string */ export function formatDuration( createdDate: string | null | undefined, resolvedDate: string | null | undefined ): string { const created = createdDate ? new Date(createdDate) : null const resolved = resolvedDate ? new Date(resolvedDate) : null if (!created || !resolved) return "" const diffMs = resolved.getTime() - created.getTime() if (diffMs < 0) return "" const totalSeconds = Math.floor(diffMs / 1000) let hours = Math.floor(totalSeconds / 3600) let minutes = Math.floor((totalSeconds % 3600) / 60) let seconds = totalSeconds % 60 // if seconds are close to 60, round up to next minute // if minutes are close to 60, round up to next hour if (seconds >= 58) { minutes += 1 seconds = 0 } if (minutes >= 60) { hours += 1 minutes = 0 } // For durations over 1 hour, omit seconds for cleaner display if (hours > 0) { return [hours ? `${hours}h` : null, minutes ? `${minutes}m` : null].filter(Boolean).join(" ") } return [hours ? `${hours}h` : null, minutes ? `${minutes}m` : null, seconds ? `${seconds}s` : null] .filter(Boolean) .join(" ") } /** Parse semver string into major, minor, and patch numbers * @example * const semVer = "1.2.3" * const { major, minor, patch } = parseSemVer(semVer) * console.log(major, minor, patch) // 1, 2, 3 */ export const parseSemVer = (semVer = ""): SemVer => { // if (semVer.startsWith("v")) { // semVer = semVer.slice(1) // } if (semVer.includes("-")) { semVer = semVer.slice(0, semVer.indexOf("-")) } const parts = semVer.split(".").map(Number) return { major: parts?.[0] ?? 0, minor: parts?.[1] ?? 0, patch: parts?.[2] ?? 0 } } /** Compare two semver strings. Returns -1 if a is less than b, 0 if a is equal to b, and 1 if a is greater than b. */ export function compareSemVer(a: SemVer, b: SemVer) { if (a.major !== b.major) { return a.major - b.major } if (a.minor !== b.minor) { return a.minor - b.minor } return a.patch - b.patch } const MIN_NETWORK_MONITOR_AGENT_VERSION = parseSemVer("0.20.0") export function supportsNetworkMonitors(system: Pick) { return compareSemVer(parseSemVer(system.info?.v), MIN_NETWORK_MONITOR_AGENT_VERSION) >= 0 } // biome-ignore lint/suspicious/noExplicitAny: any is used to allow any function to be passed in export function debounce any>(func: T, wait: number): (...args: Parameters) => void { let timeout: ReturnType return (...args: Parameters) => { clearTimeout(timeout) timeout = setTimeout(() => func(...args), wait) } } /** Debounce separately per key, so a pending call for one key is never replaced by a call for another */ // biome-ignore lint/suspicious/noExplicitAny: any is used to allow any function to be passed in export function debounceByKey any>( func: T, wait: number ): (key: string, ...args: Parameters) => void { const timeouts = new Map>() return (key: string, ...args: Parameters) => { clearTimeout(timeouts.get(key)) timeouts.set( key, setTimeout(() => { timeouts.delete(key) func(...args) }, wait) ) } } // Cache for runOnce // biome-ignore lint/complexity/noBannedTypes: Function is used to allow any function to be passed in const runOnceCache = new WeakMap() /** Run a function only once */ // biome-ignore lint/suspicious/noExplicitAny: any is used to allow any function to be passed in export function runOnce any>(fn: T): T { return ((...args: Parameters) => { let state = runOnceCache.get(fn) if (!state) { state = { done: false, result: undefined } runOnceCache.set(fn, state) } if (!state.done) { state.result = fn(...args) state.done = true } return state.result }) as T } /** Parses a filter string into OR'd groups of AND'd terms: "a b, c" -> [["a","b"], ["c"]] */ export function parseFilterGroups(value: string): string[][] { return value .toLowerCase() .split(",") .map((group) => group.trim().split(" ").filter((term) => term.length > 0)) .filter((terms) => terms.length > 0) } /** True if every term in at least one OR'd group is found in searchString. */ export function matchesFilterGroups(searchString: string, groups: string[][]): boolean { return groups.some((terms) => terms.every((term) => searchString.includes(term))) } /** Format seconds to hours, minutes, or seconds */ export function secondsToString(seconds: number, unit: "hour" | "minute" | "day"): string { const count = Math.floor(seconds / (unit === "hour" ? 3600 : unit === "minute" ? 60 : 86400)) const countString = formatNumber(count) switch (unit) { case "minute": return plural(count, { one: `${countString} minute`, few: `${countString} minutes`, many: `${countString} minutes`, other: `${countString} minutes`, }) case "hour": return plural(count, { one: `${countString} hour`, other: `${countString} hours` }) case "day": return plural(count, { one: `${countString} day`, other: `${countString} days` }) } } /** Format seconds to uptime string - "X minutes", "X hours", "X days" */ export function secondsToUptimeString(seconds: number): string { if (seconds < 3600) { return secondsToString(seconds, "minute") } else if (seconds < 360000) { return secondsToString(seconds, "hour") } else { return secondsToString(seconds, "day") } }