Dough Git

clove/email

src/web/lib/format.ts

back to src/web/lib

export function fmtTime(ms: number): string {
  const d = new Date(ms);
  const now = new Date();
  if (d.toDateString() === now.toDateString()) {
    return d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
  }
  if (d.getFullYear() === now.getFullYear()) {
    return d.toLocaleDateString(undefined, { day: "numeric", month: "short" });
  }
  return d.toLocaleDateString();
}

export function fmtSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

/** "Ari <ari@x.y>" -> "Ari"; a bare address stays as it is. */
export function displayName(addr: string): string {
  const name = addr.replace(/<[^>]*>/, "").replace(/"/g, "").trim();
  return name || addr.replace(/[<>]/g, "");
}

/** "Ari <ari@x.y>" -> "ari@x.y". */
export function bareAddress(addr: string): string {
  return (addr.match(/<([^<>]+)>/)?.[1] ?? addr).trim();
}

export function isAddress(addr: string): boolean {
  return /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(bareAddress(addr));
}

/** Splits on , ; and newlines, except inside quotes: "Doe, Jane" <j@x.y> stays whole. */
export function splitList(raw: string): string[] {
  return (raw.match(/(?:"[^"]*"?|[^,;\n"])+/g) ?? []).map((s) => s.trim()).filter(Boolean);
}