Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 21 additions & 32 deletions packages/cubejs-client-core/src/format-d3-numeric-locale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,22 @@ import { formatLocale } from 'd3-format';

import type { FormatLocaleDefinition, FormatLocaleObject } from 'd3-format';

import enUS from 'd3-format/locale/en-US.json';
import enGB from 'd3-format/locale/en-GB.json';
import zhCN from 'd3-format/locale/zh-CN.json';
import esES from 'd3-format/locale/es-ES.json';
import esMX from 'd3-format/locale/es-MX.json';
import deDE from 'd3-format/locale/de-DE.json';
import jaJP from 'd3-format/locale/ja-JP.json';
import frFR from 'd3-format/locale/fr-FR.json';
import ptBR from 'd3-format/locale/pt-BR.json';
import koKR from 'd3-format/locale/ko-KR.json';
import itIT from 'd3-format/locale/it-IT.json';
import nlNL from 'd3-format/locale/nl-NL.json';
import ruRU from 'd3-format/locale/ru-RU.json';

// Pre-built d3 locale definitions for the most popular locales.
// Used as a fallback when Intl is unavailable (e.g. some edge runtimes).
export const formatD3NumericLocale: Record<string, FormatLocaleDefinition> = {
'en-US': enUS as unknown as FormatLocaleDefinition,
'en-GB': enGB as unknown as FormatLocaleDefinition,
'zh-CN': zhCN as unknown as FormatLocaleDefinition,
'es-ES': esES as unknown as FormatLocaleDefinition,
'es-MX': esMX as unknown as FormatLocaleDefinition,
'de-DE': deDE as unknown as FormatLocaleDefinition,
'ja-JP': jaJP as unknown as FormatLocaleDefinition,
'fr-FR': frFR as unknown as FormatLocaleDefinition,
'pt-BR': ptBR as unknown as FormatLocaleDefinition,
'ko-KR': koKR as unknown as FormatLocaleDefinition,
'it-IT': itIT as unknown as FormatLocaleDefinition,
'nl-NL': nlNL as unknown as FormatLocaleDefinition,
'ru-RU': ruRU as unknown as FormatLocaleDefinition,
export const formatD3NumericLocale: Record<string, Omit<FormatLocaleDefinition, 'currency'>> = {
'en-US': { decimal: '.', thousands: ',', grouping: [3] },
'en-GB': { decimal: '.', thousands: ',', grouping: [3] },
'zh-CN': { decimal: '.', thousands: ',', grouping: [3] },
'es-ES': { decimal: ',', thousands: '.', grouping: [3] },
'es-MX': { decimal: '.', thousands: ',', grouping: [3] },
'de-DE': { decimal: ',', thousands: '.', grouping: [3] },
'ja-JP': { decimal: '.', thousands: ',', grouping: [3] },
'fr-FR': { decimal: ',', thousands: '\u00a0', grouping: [3], percent: '\u202f%' },
'pt-BR': { decimal: ',', thousands: '.', grouping: [3] },
'ko-KR': { decimal: '.', thousands: ',', grouping: [3] },
'it-IT': { decimal: ',', thousands: '.', grouping: [3] },
'nl-NL': { decimal: ',', thousands: '.', grouping: [3] },
'ru-RU': { decimal: ',', thousands: '\u00a0', grouping: [3] },
};

const currencySymbols: Record<string, string> = {
Expand All @@ -45,7 +31,7 @@ const currencySymbols: Record<string, string> = {
RUB: '₽',
};

function getCurrencySymbol(locale: string | undefined, currencyCode: string): [string, string] {
function getCurrencyOverride(locale: string | undefined, currencyCode: string): [string, string] {
try {
const cf = new Intl.NumberFormat(locale, { style: 'currency', currency: currencyCode });
const currencyParts = cf.formatToParts(1);
Expand Down Expand Up @@ -88,7 +74,7 @@ function getD3NumericLocaleFromIntl(locale: string, currencyCode = 'USD'): Forma
decimal: find('decimal') || '.',
thousands: find('group') || ',',
grouping: deriveGrouping(locale),
currency: getCurrencySymbol(locale, currencyCode),
currency: getCurrencyOverride(locale, currencyCode),
};
}

Expand All @@ -103,14 +89,17 @@ export function getD3NumericLocale(locale: string, currencyCode = 'USD'): Format
let definition: FormatLocaleDefinition;

if (formatD3NumericLocale[locale]) {
definition = { ...formatD3NumericLocale[locale], currency: getCurrencySymbol(locale, currencyCode) };
definition = { ...formatD3NumericLocale[locale], currency: getCurrencyOverride(locale, currencyCode) };
} else {
try {
definition = getD3NumericLocaleFromIntl(locale, currencyCode);
} catch (e: unknown) {
console.warn('Failed to generate d3 local via Intl, failing back to en-US', e);

definition = formatD3NumericLocale['en-US'];
definition = {
...formatD3NumericLocale['en-US'],
currency: getCurrencyOverride(locale, currencyCode)
};
}
}

Expand Down
185 changes: 131 additions & 54 deletions packages/cubejs-client-core/src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,27 +26,57 @@ const currentLocale = detectLocale();

const DEFAULT_DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S';
const DEFAULT_DATE_FORMAT = '%Y-%m-%d';
const DEFAULT_DATE_MONTH_FORMAT = '%Y-%m';
const DEFAULT_DATE_WEEK_FORMAT = '%Y-%m-%d W%V';
const DEFAULT_DATE_MONTH_FORMAT = '%Y %b';
const DEFAULT_DATE_QUARTER_FORMAT = '%Y-Q%q';
const DEFAULT_DATE_YEAR_FORMAT = '%Y';

function getTimeFormatByGrain(grain: string | undefined): string {
switch (grain) {
case 'day':
case 'week':
return DEFAULT_DATE_FORMAT;
case 'month':
return DEFAULT_DATE_MONTH_FORMAT;
case 'quarter':
return DEFAULT_DATE_QUARTER_FORMAT;
case 'year':
return DEFAULT_DATE_YEAR_FORMAT;
case 'second':
case 'minute':
case 'hour':
default:
return DEFAULT_DATETIME_FORMAT;
function getFormatByGrain(grain?: string): string {
// Grains that should show date and time (sub-day granularities)
const dateTimeGrains = ['second', 'minute', 'hour'];

// Grains that should show date only (day and above granularities)
const dateOnlyGrains = ['day', 'week', 'month', 'quarter', 'year'];

if (grain === 'day') {
return DEFAULT_DATE_FORMAT;
}

if (grain === 'week') {
return DEFAULT_DATE_WEEK_FORMAT;
}

if (grain === 'month') {
return DEFAULT_DATE_MONTH_FORMAT;
}

if (grain === 'quarter') {
return DEFAULT_DATE_QUARTER_FORMAT;
}

if (grain === 'year') {
return DEFAULT_DATE_YEAR_FORMAT;
}

if (!grain || dateTimeGrains.includes(grain)) {
return DEFAULT_DATETIME_FORMAT;
}

if (dateOnlyGrains.includes(grain)) {
return DEFAULT_DATE_FORMAT;
}

// Fallback to datetime for unknown grains
return DEFAULT_DATETIME_FORMAT;
}

export function formatDateByGranularity(value: Date | string | number, granularity?: string): string {
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) {
return 'Invalid date';
}

return timeFormat(getFormatByGrain(granularity))(date);
}

function parseNumber(value: any): number {
Expand All @@ -73,78 +103,125 @@ export type FormatValueOptions = FormatValueMember & {
emptyPlaceholder?: string;
};

export function formatValue(
value: any,
{ type, format, currency = 'USD', granularity, locale = currentLocale, emptyPlaceholder = '∅' }: FormatValueOptions
): string {
if (value === null || value === undefined) {
return emptyPlaceholder;
export type GetFormatOptions = {
locale?: string;
};

export type GetFormatResult = {
formatString: string | null;
formatFunc: (value: any) => string;
};

function formatBoolean(value: any): string {
if (typeof value === 'boolean') {
return value.toString();
}

if (type === 'boolean') {
if (typeof value === 'boolean') {
return value.toString();
}
if (typeof value === 'number') {
return Boolean(value).toString();
}

if (typeof value === 'number') {
return Boolean(value).toString();
}
// Some SQL drivers return booleans as '0'/'1' or 'true'/'false' strings, It's incorrect behaivour in Cube,
// but let's format it as boolean for backward compatibility.
if (value === '0' || value === 'false') {
return 'false';
}

// Some SQL drivers return booleans as '0'/'1' or 'true'/'false' strings, It's incorrect behaivour in Cube,
// but let's format it as boolean for backward compatibility.
if (value === '0' || value === 'false') {
return 'false';
}
if (value === '1' || value === 'true') {
return 'true';
}

if (value === '1' || value === 'true') {
return 'true';
}
return String(value);
}

export function getFormat(
member: FormatValueMember,
{ locale = currentLocale }: GetFormatOptions = {}
): GetFormatResult {
const { type, format, currency = 'USD', granularity } = member;

return String(value);
if (type === 'boolean') {
return { formatString: null, formatFunc: formatBoolean };
}

if (format && typeof format === 'object') {
if (format.type === 'custom-numeric') {
return d3Format(format.value)(parseNumber(value));
return {
formatString: format.value,
formatFunc: (value) => d3Format(format.value)(parseNumber(value)),
};
}

if (format.type === 'custom-time') {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? 'Invalid date' : timeFormat(format.value)(date);
return {
formatString: format.value,
formatFunc: (value) => {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? 'Invalid date' : timeFormat(format.value)(date);
},
};
}

// { type: 'link', label: string } — return value as string
return String(value);
return { formatString: null, formatFunc: (value) => String(value) };
}

if (typeof format === 'string') {
switch (format) {
case 'currency':
return getD3NumericLocale(locale, currency).format(DEFAULT_CURRENCY_FORMAT)(parseNumber(value));
return {
formatString: DEFAULT_CURRENCY_FORMAT,
formatFunc: (value) => getD3NumericLocale(locale, currency).format(DEFAULT_CURRENCY_FORMAT)(parseNumber(value)),
};
case 'percent':
return getD3NumericLocale(locale).format(DEFAULT_PERCENT_FORMAT)(parseNumber(value));
return {
formatString: DEFAULT_PERCENT_FORMAT,
formatFunc: (value) => getD3NumericLocale(locale).format(DEFAULT_PERCENT_FORMAT)(parseNumber(value)),
};
case 'number':
return getD3NumericLocale(locale).format(DEFAULT_NUMBER_FORMAT)(parseNumber(value));
return {
formatString: DEFAULT_NUMBER_FORMAT,
formatFunc: (value) => getD3NumericLocale(locale).format(DEFAULT_NUMBER_FORMAT)(parseNumber(value)),
};
case 'id':
return d3Format(DEFAULT_ID_FORMAT)(parseNumber(value));
return {
formatString: DEFAULT_ID_FORMAT,
formatFunc: (value) => d3Format(DEFAULT_ID_FORMAT)(parseNumber(value)),
};
case 'imageUrl':
case 'link':
default:
return String(value);
return { formatString: null, formatFunc: (value) => String(value) };
}
}

// No explicit format — infer from type
if (type === 'time') {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return 'Invalid date';

return timeFormat(getTimeFormatByGrain(granularity))(date);
return {
formatString: getFormatByGrain(granularity),
formatFunc: (value) => formatDateByGranularity(value, granularity),
};
}

if (type === 'number') {
return getD3NumericLocale(locale, currency).format(DEFAULT_NUMBER_FORMAT)(parseNumber(value));
return {
formatString: DEFAULT_NUMBER_FORMAT,
formatFunc: (value) => getD3NumericLocale(locale, currency).format(DEFAULT_NUMBER_FORMAT)(parseNumber(value)),
};
}

return String(value);
return { formatString: null, formatFunc: (value) => String(value) };
}

export function formatValue(
value: any,
options: FormatValueOptions
): string {
const { emptyPlaceholder = '∅' } = options;

if (value === null || value === undefined) {
return emptyPlaceholder;
}

return getFormat(options, { locale: options.locale }).formatFunc(value);
}
Loading
Loading