All files / src/lib format.ts

94.87% Statements 37/39
92.5% Branches 37/40
100% Functions 16/16
94.87% Lines 37/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215            41x               2778x 1x   2777x                       91x 2x   89x             41x       1690x 1690x     1690x 5x     1685x                   154x               41x             46x 1x   45x               46x               506x         506x                           118x                     44x     44x                       13x                         198x         198x         120x 120x       120x         168x 167x         167x                 98x 98x                 111x                       129x        
// Standalone values (amounts in tables and cards, dates in lists) are
// formatted here, in the language's own format (CONCEPT.md, i18n). Messages
// that contain a value get it already formatted from these helpers.
import { getLocale, type Locale } from '#/paraglide/runtime.js'
 
/** The Intl locale for each app language: the language as used in Finland. */
export const INTL_LOCALES = {
  fi: 'fi-FI',
  sv: 'sv-FI',
  en: 'en-FI',
} as const satisfies Record<Locale, string>
 
/** Euros from integer cents, e.g. 123456 → "1 234,56 €" in Finnish. */
export function formatMoney(cents: number, locale: Locale = getLocale()) {
  if (!Number.isSafeInteger(cents)) {
    throw new RangeError(`Money must be integer cents, got ${String(cents)}`)
  }
  return new Intl.NumberFormat(INTL_LOCALES[locale], {
    style: 'currency',
    currency: 'EUR',
  }).format(cents / 100)
}
 
/**
 * Whole euros from integer cents, e.g. 126200 → "1 262 €" in Finnish and
 * "€1,262" in English. For figures that are rounded to whole euros already,
 * such as an estimate: cents that aren't whole euros are refused.
 */
export function formatEuros(cents: number, locale: Locale = getLocale()) {
  if (!Number.isSafeInteger(cents) || cents % 100 !== 0) {
    throw new RangeError(`Expected whole euros in cents, got ${String(cents)}`)
  }
  return new Intl.NumberFormat(INTL_LOCALES[locale], {
    style: 'currency',
    currency: 'EUR',
    maximumFractionDigits: 0,
  }).format(cents / 100)
}
 
const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/
 
/** A calendar date, e.g. "2026-03-05" → "5.3.2026" in Finnish. */
export function formatDate(iso: string, locale: Locale = getLocale()) {
  const [, year, month, day] = ISO_DATE.exec(iso) ?? []
  const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)))
  // Rejects malformed strings (an invalid date throws in toISOString) and
  // dates that roll over, such as 2026-02-30.
  if (isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== iso) {
    throw new RangeError(`Not an ISO date (YYYY-MM-DD): ${iso}`)
  }
  // The date has no time of day; format it in UTC so it never shifts a day.
  return new Intl.DateTimeFormat(INTL_LOCALES[locale], {
    timeZone: 'UTC',
  }).format(date)
}
 
/**
 * The day of a point in time, as it was in Finland, e.g. when an invitation
 * was sent: "20.11.2026" in Finnish.
 */
export function formatDay(instant: Date, locale: Locale = getLocale()) {
  return new Intl.DateTimeFormat(INTL_LOCALES[locale], {
    timeZone: 'Europe/Helsinki',
  }).format(instant)
}
 
// Plain numbers: ICU formats en-FI numbers the Finnish way ("48,5") but
// en-FI money the English way ("€1,234.56"), so English uses en-GB here to
// match the money format's decimal point.
const NUMBER_LOCALES = {
  ...INTL_LOCALES,
  en: 'en-GB',
} as const satisfies Record<Locale, string>
 
/** A one-decimal quantity from integer tenths, e.g. 485 → "48,5" in Finnish. */
export function formatTenths(tenths: number, locale: Locale = getLocale()) {
  if (!Number.isSafeInteger(tenths)) {
    throw new RangeError(`Expected integer tenths, got ${String(tenths)}`)
  }
  return new Intl.NumberFormat(NUMBER_LOCALES[locale], {
    maximumFractionDigits: 1,
    useGrouping: false,
  }).format(tenths / 10)
}
 
/** A floor area from tenths of m², e.g. 485 → "48,5 m²" in Finnish. */
export function formatArea(tenths: number, locale: Locale = getLocale()) {
  return `${formatTenths(tenths, locale)}\u00a0m²`
}
 
/**
 * An ownership share from basis points, e.g. 5000 → "50 %" and 3333 →
 * "33,33 %" in Finnish, "50%" in English.
 */
export function formatShare(basisPoints: number, locale: Locale = getLocale()) {
  Iif (!Number.isSafeInteger(basisPoints)) {
    throw new RangeError(
      `Expected integer basis points, got ${String(basisPoints)}`,
    )
  }
  return new Intl.NumberFormat(NUMBER_LOCALES[locale], {
    style: 'percent',
    maximumFractionDigits: 2,
  }).format(basisPoints / 10000)
}
 
/**
 * A share as a number to edit in percent, without the sign: 3333 → "33,33"
 * in Finnish and "33.33" in English, as parsePercent() reads it back.
 */
export function formatPercentNumber(
  basisPoints: number,
  locale: Locale = getLocale(),
) {
  return new Intl.NumberFormat(NUMBER_LOCALES[locale], {
    maximumFractionDigits: 2,
    useGrouping: false,
  }).format(basisPoints / 100)
}
 
/**
 * A change of money with its sign, e.g. a new rent against the old one:
 * "+12,00 €" or "−12,00 €" in Finnish, "+€12.00" in English.
 */
export function formatMoneyChange(cents: number, locale: Locale = getLocale()) {
  Iif (!Number.isSafeInteger(cents)) {
    throw new RangeError(`Money must be integer cents, got ${String(cents)}`)
  }
  return new Intl.NumberFormat(INTL_LOCALES[locale], {
    style: 'currency',
    currency: 'EUR',
    signDisplay: 'exceptZero',
  }).format(cents / 100)
}
 
/** A relative change in percent, one decimal, with its sign: "+5,6 %". */
export function formatPercentChange(
  percent: number,
  locale: Locale = getLocale(),
) {
  return new Intl.NumberFormat(NUMBER_LOCALES[locale], {
    style: 'percent',
    maximumFractionDigits: 1,
    signDisplay: 'exceptZero',
  }).format(percent / 100)
}
 
/** A month as a heading, e.g. 2026, 11 → "Marraskuu 2026" in Finnish. */
export function formatMonth(
  year: number,
  month: number,
  locale: Locale = getLocale(),
) {
  const text = new Intl.DateTimeFormat(INTL_LOCALES[locale], {
    timeZone: 'UTC',
    month: 'long',
    year: 'numeric',
  }).format(new Date(Date.UTC(year, month - 1, 1)))
  return text.charAt(0).toLocaleUpperCase(INTL_LOCALES[locale]) + text.slice(1)
}
 
/** A month's name alone, e.g. "2026-11" → "Marraskuu" in Finnish. */
export function formatMonthName(month: string, locale: Locale = getLocale()) {
  const [year, number] = month.split('-').map(Number) as [number, number]
  const text = new Intl.DateTimeFormat(INTL_LOCALES[locale], {
    timeZone: 'UTC',
    month: 'long',
  }).format(new Date(Date.UTC(year, number - 1, 1)))
  return text.charAt(0).toLocaleUpperCase(INTL_LOCALES[locale]) + text.slice(1)
}
 
/** A date without its year, e.g. "2026-11-12" → "12.11." in Finnish. */
export function formatDayMonth(iso: string, locale: Locale = getLocale()) {
  formatDate(iso, locale) // validates
  const [year, month, day] = iso.split('-').map(Number) as [
    number,
    number,
    number,
  ]
  return new Intl.DateTimeFormat(INTL_LOCALES[locale], {
    timeZone: 'UTC',
    day: 'numeric',
    month: 'numeric',
  }).format(new Date(Date.UTC(year, month - 1, day)))
}
 
/** A file size: "412 kt" under a megabyte, "2,3 Mt" above, in Finnish. */
export function formatFileSize(bytes: number, locale: Locale = getLocale()) {
  const megabytes = bytes >= 1024 * 1024
  return new Intl.NumberFormat(NUMBER_LOCALES[locale], {
    style: 'unit',
    unit: megabytes ? 'megabyte' : 'kilobyte',
    maximumFractionDigits: megabytes ? 1 : 0,
  }).format(megabytes ? bytes / (1024 * 1024) : Math.max(1, bytes / 1024))
}
 
/** Cents as an amount to edit in a field, without grouping: "1234,50". */
export function formatAmountInput(cents: number, locale: Locale = getLocale()) {
  return new Intl.NumberFormat(NUMBER_LOCALES[locale], {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
    useGrouping: false,
  }).format(cents / 100)
}
 
/** A list as a sentence lists it: "A, B and C" in English, "A, B ja C" in Finnish. */
export function formatList(
  items: readonly string[],
  locale: Locale = getLocale(),
) {
  return new Intl.ListFormat(INTL_LOCALES[locale], {
    type: 'conjunction',
  }).format(items)
}