|
| 1 | +import type { MetricColumnMeta } from "shared"; |
| 2 | + |
| 3 | +// ============================================================================ |
| 4 | +// Pure Format Utilities |
| 5 | +// ============================================================================ |
| 6 | +// Library-agnostic, tree-shakeable helpers for turning raw metric values and |
| 7 | +// column metadata into display strings. These take the UC/YAML format spec (or |
| 8 | +// MetricColumnMeta) as ARGUMENTS — no React, no chart-lib coupling, no bundled |
| 9 | +// artifact — so they can be used from any surface (tables, tooltips, charts). |
| 10 | + |
| 11 | +/** |
| 12 | + * Counts the number of fractional digits declared by a numeric format spec. |
| 13 | + * E.g. "#,##0.00" -> 2, "#,##0" -> 0, "0.0%" -> 1. |
| 14 | + */ |
| 15 | +function countDecimals(format: string): number { |
| 16 | + const dotIndex = format.indexOf("."); |
| 17 | + if (dotIndex === -1) return 0; |
| 18 | + const frac = format.slice(dotIndex + 1); |
| 19 | + const match = frac.match(/^[0#]+/); |
| 20 | + return match ? match[0].length : 0; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Best-effort coercion of an arbitrary value to a finite number. Handles the |
| 25 | + * common wire shapes (number, bigint, numeric string). Returns null when the |
| 26 | + * value cannot be meaningfully treated as a number. |
| 27 | + */ |
| 28 | +function coerceNumber(value: unknown): number | null { |
| 29 | + if (typeof value === "number") return Number.isFinite(value) ? value : null; |
| 30 | + if (typeof value === "bigint") return Number(value); |
| 31 | + if (typeof value === "string") { |
| 32 | + if (value.trim() === "") return null; |
| 33 | + const n = Number(value); |
| 34 | + return Number.isFinite(n) ? n : null; |
| 35 | + } |
| 36 | + return null; |
| 37 | +} |
| 38 | + |
| 39 | +/** Format a number with fixed decimals + optional thousands grouping. */ |
| 40 | +function formatNumber( |
| 41 | + value: number, |
| 42 | + decimals: number, |
| 43 | + grouping: boolean, |
| 44 | +): string { |
| 45 | + return value.toLocaleString("en-US", { |
| 46 | + minimumFractionDigits: decimals, |
| 47 | + maximumFractionDigits: decimals, |
| 48 | + useGrouping: grouping, |
| 49 | + }); |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Format a raw value using a UC/YAML printf-style format spec. |
| 54 | + * |
| 55 | + * Recognizes the common spreadsheet-style specs: |
| 56 | + * - currency prefix, e.g. `"$#,##0.00"` (1234.5 -> "$1,234.50") |
| 57 | + * - thousands grouping + N decimals, e.g. `"#,##0"` (1234567 -> "1,234,567") |
| 58 | + * or `"#,##0.00"` (1234.5 -> "1,234.50") |
| 59 | + * - percent, e.g. `"0.0%"` (0.1234 -> "12.3%") — the value is multiplied by 100 |
| 60 | + * |
| 61 | + * No format spec -> sensible default: numbers via `toLocaleString`, everything |
| 62 | + * else via `String()`. `null`/`undefined` -> `""`. Unrecognized specs fall back |
| 63 | + * to a best-effort result (the number grouped, or `String(value)`). |
| 64 | + */ |
| 65 | +export function formatValue(value: unknown, format?: string): string { |
| 66 | + if (value === null || value === undefined) return ""; |
| 67 | + |
| 68 | + if (!format) { |
| 69 | + if (typeof value === "number") { |
| 70 | + return Number.isFinite(value) ? value.toLocaleString() : String(value); |
| 71 | + } |
| 72 | + if (typeof value === "bigint") return value.toLocaleString(); |
| 73 | + return String(value); |
| 74 | + } |
| 75 | + |
| 76 | + const num = coerceNumber(value); |
| 77 | + // Non-numeric value with a numeric-ish spec: nothing sensible to format. |
| 78 | + if (num === null) return String(value); |
| 79 | + |
| 80 | + const isPercent = format.includes("%"); |
| 81 | + const isCurrency = format.includes("$"); |
| 82 | + const grouping = format.includes(","); |
| 83 | + const decimals = countDecimals(format); |
| 84 | + |
| 85 | + if (isPercent) { |
| 86 | + return `${formatNumber(num * 100, decimals, grouping)}%`; |
| 87 | + } |
| 88 | + |
| 89 | + if (isCurrency) { |
| 90 | + const sign = num < 0 ? "-" : ""; |
| 91 | + return `${sign}$${formatNumber(Math.abs(num), decimals, grouping)}`; |
| 92 | + } |
| 93 | + |
| 94 | + return formatNumber(num, decimals, grouping); |
| 95 | +} |
| 96 | + |
| 97 | +/** |
| 98 | + * Turns a raw column name into a human-readable label. |
| 99 | + * Handles camelCase, snake_case, acronyms, and ALL_CAPS. |
| 100 | + * E.g., "totalSpend" -> "Total Spend", "avg_ltv" -> "Avg Ltv". |
| 101 | + */ |
| 102 | +function humanize(name: string): string { |
| 103 | + return ( |
| 104 | + name |
| 105 | + // Handle consecutive uppercase followed by lowercase (e.g., HTTPUrl -> HTTP Url) |
| 106 | + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") |
| 107 | + // Handle lowercase followed by uppercase (e.g., totalSpend -> total Spend) |
| 108 | + .replace(/([a-z])([A-Z])/g, "$1 $2") |
| 109 | + // Replace underscores with spaces |
| 110 | + .replace(/_/g, " ") |
| 111 | + // Collapse multiple spaces into one |
| 112 | + .replace(/\s+/g, " ") |
| 113 | + // Normalize to title case |
| 114 | + .toLowerCase() |
| 115 | + .replace(/\b\w/g, (l) => l.toUpperCase()) |
| 116 | + .trim() |
| 117 | + ); |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Human label for a column: prefers `columnMeta.display_name`, else humanizes |
| 122 | + * the raw column name (camelCase / snake_case / CAPS -> Title Case). |
| 123 | + */ |
| 124 | +export function formatLabel( |
| 125 | + name: string, |
| 126 | + columnMeta?: MetricColumnMeta, |
| 127 | +): string { |
| 128 | + if (columnMeta?.display_name) return columnMeta.display_name; |
| 129 | + return humanize(name); |
| 130 | +} |
| 131 | + |
| 132 | +/** |
| 133 | + * Maps a UC/spreadsheet-style format spec to a |
| 134 | + * [d3-format](https://d3js.org/d3-format) specifier string, for charts that |
| 135 | + * consume d3 format strings. |
| 136 | + * |
| 137 | + * Best-effort mapping for the common specs: |
| 138 | + * - `"$#,##0.00"` -> `"$,.2f"` |
| 139 | + * - `"#,##0"` -> `",.0f"` |
| 140 | + * - `"#,##0.00"` -> `",.2f"` |
| 141 | + * - `"0.0%"` -> `".1%"` |
| 142 | + * |
| 143 | + * No spec, or a spec that is not a recognizable numeric pattern -> `undefined`. |
| 144 | + */ |
| 145 | +export function toD3Format(format?: string): string | undefined { |
| 146 | + if (!format) return undefined; |
| 147 | + |
| 148 | + // Only map specs built purely from numeric-format characters; anything else |
| 149 | + // (date patterns, free text, ...) is left unrecognized. |
| 150 | + if (format.replace(/[#0,.$%\s]/g, "") !== "") return undefined; |
| 151 | + if (!/[0#]/.test(format)) return undefined; |
| 152 | + |
| 153 | + const group = format.includes(",") ? "," : ""; |
| 154 | + const decimals = countDecimals(format); |
| 155 | + |
| 156 | + if (format.includes("%")) { |
| 157 | + return `${group}.${decimals}%`; |
| 158 | + } |
| 159 | + |
| 160 | + const prefix = format.includes("$") ? "$" : ""; |
| 161 | + return `${prefix}${group}.${decimals}f`; |
| 162 | +} |
0 commit comments