utils.ts raw

   1  import { clsx, type ClassValue } from "clsx";
   2  import { ALBY_ACCOUNT_APP_NAME } from "src/constants";
   3  import { BudgetRenewalType } from "src/types";
   4  import { twMerge } from "tailwind-merge";
   5  
   6  export function cn(...inputs: ClassValue[]) {
   7    return twMerge(clsx(inputs));
   8  }
   9  
  10  export function formatAmount(amountMsat: number, decimals = 1) {
  11    amountMsat /= 1000; // msat to sat
  12    let i = 0;
  13    for (i; amountMsat >= 1000; i++) {
  14      amountMsat /= 1000;
  15    }
  16    return amountMsat.toFixed(i > 0 ? decimals : 0) + ["", "k", "M", "G"][i];
  17  }
  18  
  19  export function splitSocketAddress(socketAddress?: string) {
  20    if (!socketAddress) {
  21      return { address: "", port: "" };
  22    }
  23    const lastColonIndex = socketAddress.lastIndexOf(":");
  24    if (lastColonIndex <= 0) {
  25      return { address: "", port: "" };
  26    }
  27    const address = socketAddress.slice(0, lastColonIndex);
  28    const port = socketAddress.slice(lastColonIndex + 1);
  29    return { address, port };
  30  }
  31  
  32  export function generatePageNumbers(currentPage: number, totalPages: number) {
  33    const MAX_PAGES_TO_SHOW = 3;
  34    const pageNumbers: (number | "ellipsis")[] = [];
  35    const half = Math.floor(MAX_PAGES_TO_SHOW / 2);
  36  
  37    let start = Math.max(1, currentPage - half);
  38    let end = Math.min(totalPages, currentPage + half);
  39  
  40    if (currentPage - half <= 0) {
  41      end = Math.min(totalPages, MAX_PAGES_TO_SHOW);
  42    }
  43  
  44    if (currentPage + half > totalPages) {
  45      start = Math.max(1, totalPages - MAX_PAGES_TO_SHOW + 1);
  46    }
  47  
  48    for (let index = start; index <= end; index++) {
  49      pageNumbers.push(index);
  50    }
  51  
  52    if (start > 1) {
  53      if (start > 2) {
  54        pageNumbers.unshift(1, "ellipsis");
  55      } else {
  56        pageNumbers.unshift(1);
  57      }
  58    }
  59  
  60    if (end < totalPages - 1) {
  61      pageNumbers.push("ellipsis", totalPages);
  62    } else if (end === totalPages - 1) {
  63      pageNumbers.push(totalPages);
  64    }
  65  
  66    return pageNumbers;
  67  }
  68  
  69  export function getBudgetRenewalLabel(renewalType: BudgetRenewalType): string {
  70    switch (renewalType) {
  71      case "daily":
  72        return "day";
  73      case "weekly":
  74        return "week";
  75      case "monthly":
  76        return "month";
  77      case "yearly":
  78        return "year";
  79      case "never":
  80        return "never";
  81      case "":
  82        return "";
  83    }
  84  }
  85  
  86  export function getAppDisplayName(name: string) {
  87    return name === ALBY_ACCOUNT_APP_NAME ? "Alby Account" : name;
  88  }
  89