Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: use user's (or configured) locale for dates, times, and numbers (#6433)

Myles Scolnick47105c0c4833
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 702e5471b5..497a53c626 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -109,6 +109,7 @@ export const activeUserConfigCategoryAtom = atom<SettingCategoryId>(
);
const FORM_DEBOUNCE = 100; // ms;
+const LOCALE_SYSTEM_VALUE = "__system__";
export const UserConfigForm: React.FC = () => {
const [config, setConfig] = useUserConfig();
@@ -748,6 +749,47 @@ export const UserConfigForm: React.FC = () => {
</FormItem>
)}
/>
+ <FormField
+ control={form.control}
+ name="display.locale"
+ render={({ field }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>Locale</FormLabel>
+ <FormControl>
+ <NativeSelect
+ data-testid="locale-select"
+ onChange={(e) => {
+ if (e.target.value === LOCALE_SYSTEM_VALUE) {
+ field.onChange(undefined);
+ } else {
+ field.onChange(e.target.value);
+ }
+ }}
+ value={field.value || LOCALE_SYSTEM_VALUE}
+ disabled={field.disabled}
+ className="inline-flex mr-2"
+ >
+ <option value={LOCALE_SYSTEM_VALUE}>System</option>
+ {navigator.languages.map((option) => (
+ <option value={option} key={option}>
+ {option}
+ </option>
+ ))}
+ </NativeSelect>
+ </FormControl>
+ <FormMessage />
+ <IsOverridden userConfig={config} name="display.locale" />
+ </FormItem>
+
+ <FormDescription>
+ The locale to use for the notebook. If your desired locale
+ is not listed, you can change it manually via{" "}
+ <Kbd className="inline">marimo config show</Kbd>.
+ </FormDescription>
+ </div>
+ )}
+ />
<FormField
control={form.control}
name="display.reference_highlighting"
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index b439c3b977..1bdd83ef06 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -18,6 +18,7 @@ import {
SquareIcon,
} from "lucide-react";
import { memo, useEffect, useMemo, useRef, useState } from "react";
+import { useLocale } from "react-aria";
import useEvent from "react-use-event-hook";
import { Button } from "@/components/ui/button";
import {
@@ -103,6 +104,7 @@ const ChatHeader: React.FC<ChatHeaderProps> = ({
}) => {
const { handleClick } = useOpenSettingsToTab();
const chatState = useAtomValue(chatStateAtom);
+ const { locale } = useLocale();
const chats = useMemo(() => {
return [...chatState.chats.values()].sort(
(a, b) => b.updatedAt - a.updatedAt,
@@ -159,7 +161,7 @@ const ChatHeader: React.FC<ChatHeaderProps> = ({
>
<div className="font-medium">{chat.title}</div>
<div className="text-sm text-muted-foreground">
- {timeAgo(chat.updatedAt)}
+ {timeAgo(chat.updatedAt, locale)}
</div>
</button>
))}
diff --git a/frontend/src/components/data-table/__tests__/column_formatting.test.ts b/frontend/src/components/data-table/__tests__/column_formatting.test.ts
index 983b7f0158..b796d0e057 100644
--- a/frontend/src/components/data-table/__tests__/column_formatting.test.ts
+++ b/frontend/src/components/data-table/__tests__/column_formatting.test.ts
@@ -6,37 +6,44 @@ import {
} from "@/utils/numbers";
import { applyFormat } from "../column-formatting/feature";
+const locale = "en-US";
+
describe("applyFormat", () => {
it("should return an empty string for null, undefined, or empty string values", () => {
- expect(applyFormat(null, { format: "Date", dataType: "date" })).toBe("");
- expect(applyFormat(undefined, { format: "Date", dataType: "date" })).toBe(
+ expect(
+ applyFormat(null, { format: "Date", dataType: "date", locale }),
+ ).toBe("");
+ expect(
+ applyFormat(undefined, { format: "Date", dataType: "date", locale }),
+ ).toBe("");
+ expect(applyFormat("", { format: "Date", dataType: "date", locale })).toBe(
"",
);
- expect(applyFormat("", { format: "Date", dataType: "date" })).toBe("");
});
describe("date formatting", () => {
it("should format date values correctly", () => {
const date = "2023-10-01T12:00:00Z";
- expect(applyFormat(date, { format: "Date", dataType: "date" })).toBe(
- "10/1/23",
- );
- expect(applyFormat(date, { format: "Datetime", dataType: "date" })).toBe(
- "10/1/23, 12:00:00 PM UTC",
- );
+ expect(
+ applyFormat(date, { format: "Date", dataType: "date", locale }),
+ ).toBe("10/1/23");
+ expect(
+ applyFormat(date, { format: "Datetime", dataType: "date", locale }),
+ ).toBe("10/1/23, 12:00:00 PM UTC");
});
it("should format time values correctly", () => {
const time = "12:00:00Z";
- expect(applyFormat(time, { format: "Time", dataType: "time" })).toBe(
- "12:00:00Z",
- );
+ expect(
+ applyFormat(time, { format: "Time", dataType: "time", locale }),
+ ).toBe("12:00:00Z");
});
it("should format datetime values correctly", () => {
const datetime = "2023-10-01T12:00:00Z";
expect(
applyFormat(datetime, {
+ locale,
format: "Datetime",
dataType: "datetime",
}),
@@ -47,26 +54,28 @@ describe("applyFormat", () => {
describe("number formatting", () => {
it("should format number values correctly", () => {
const number = "1234.567";
- expect(applyFormat(number, { format: "Auto", dataType: "number" })).toBe(
- "1,234.57",
- );
expect(
- applyFormat(number, { format: "Percent", dataType: "number" }),
+ applyFormat(number, { format: "Auto", dataType: "number", locale }),
+ ).toBe("1,234.57");
+ expect(
+ applyFormat(number, { format: "Percent", dataType: "number", locale }),
).toBe("123,456.7%");
expect(
applyFormat(number, {
+ locale,
format: "Scientific",
dataType: "number",
}),
- ).toBe(prettyScientificNumber(1234.567, { shouldRound: true }));
+ ).toBe(prettyScientificNumber(1234.567, { shouldRound: true, locale }));
expect(
applyFormat(number, {
format: "Engineering",
dataType: "number",
+ locale,
}),
- ).toBe(prettyEngineeringNumber(1234.567));
+ ).toBe(prettyEngineeringNumber(1234.567, locale));
expect(
- applyFormat(number, { format: "Integer", dataType: "number" }),
+ applyFormat(number, { format: "Integer", dataType: "number", locale }),
).toBe("1,235");
});
});
@@ -75,41 +84,47 @@ describe("applyFormat", () => {
it("should format string values correctly", () => {
const str = "hello world";
expect(
- applyFormat(str, { format: "Uppercase", dataType: "string" }),
+ applyFormat(str, { format: "Uppercase", dataType: "string", locale }),
).toBe("HELLO WORLD");
expect(
- applyFormat(str, { format: "Lowercase", dataType: "string" }),
+ applyFormat(str, { format: "Lowercase", dataType: "string", locale }),
).toBe("hello world");
expect(
- applyFormat(str, { format: "Capitalize", dataType: "string" }),
+ applyFormat(str, { format: "Capitalize", dataType: "string", locale }),
).toBe("Hello world");
- expect(applyFormat(str, { format: "Title", dataType: "string" })).toBe(
- "Hello World",
- );
+ expect(
+ applyFormat(str, { format: "Title", dataType: "string", locale }),
+ ).toBe("Hello World");
});
});
describe("boolean formatting", () => {
it("should format boolean values correctly", () => {
- expect(applyFormat(true, { format: "Yes/No", dataType: "boolean" })).toBe(
- "Yes",
- );
expect(
- applyFormat(false, { format: "Yes/No", dataType: "boolean" }),
+ applyFormat(true, { format: "Yes/No", dataType: "boolean", locale }),
+ ).toBe("Yes");
+ expect(
+ applyFormat(false, { format: "Yes/No", dataType: "boolean", locale }),
).toBe("No");
- expect(applyFormat(true, { format: "On/Off", dataType: "boolean" })).toBe(
- "On",
- );
expect(
- applyFormat(false, { format: "On/Off", dataType: "boolean" }),
+ applyFormat(true, { format: "On/Off", dataType: "boolean", locale }),
+ ).toBe("On");
+ expect(
+ applyFormat(false, { format: "On/Off", dataType: "boolean", locale }),
).toBe("Off");
});
});
it("should return the original value for unknown data types or formats", () => {
expect(
- applyFormat("some value", { format: "Auto", dataType: "unknown" }),
+ applyFormat("some value", {
+ format: "Auto",
+ dataType: "unknown",
+ locale,
+ }),
).toBe("some value");
- expect(applyFormat(123, { format: "Auto", dataType: "unknown" })).toBe(123);
+ expect(
+ applyFormat(123, { format: "Auto", dataType: "unknown", locale }),
+ ).toBe(123);
});
});
diff --git a/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx b/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx
index 1488ec2eb6..33440e734b 100644
--- a/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx
+++ b/frontend/src/components/data-table/column-explorer-panel/column-explorer.tsx
@@ -1,6 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { useState } from "react";
+import { useLocale } from "react-aria";
import {
AddDataframeChart,
renderChart,
@@ -53,6 +54,7 @@ export const ColumnExplorerPanel = ({
tableId,
}: ColumnExplorerPanelProps) => {
const [searchValue, setSearchValue] = useState("");
+ const { locale } = useLocale();
const columns = fieldTypes?.filter(([columnName]) => {
if (
columnName === SELECT_COLUMN_ID ||
@@ -71,7 +73,7 @@ export const ColumnExplorerPanel = ({
return (
<div className="mt-5 mb-3">
<span className="text-xs font-semibold ml-2 flex">
- {prettifyRowColumnCount(totalRows, totalColumns)}
+ {prettifyRowColumnCount(totalRows, totalColumns, locale)}
<CopyClipboardIcon
tooltip="Copy column names"
value={columns?.map(([columnName]) => columnName).join(",\n") || ""}
@@ -169,6 +171,7 @@ const ColumnPreview = ({
dataType: DataType;
}) => {
const { theme } = useTheme();
+ const { locale } = useLocale();
const {
data,
@@ -208,7 +211,7 @@ const ColumnPreview = ({
refetchPreview,
});
- const previewStats = stats && renderStats(stats, dataType);
+ const previewStats = stats && renderStats(stats, dataType, locale);
const chart = chart_spec && renderChart(chart_spec, theme);
diff --git a/frontend/src/components/data-table/column-formatting/feature.ts b/frontend/src/components/data-table/column-formatting/feature.ts
index 5f26f5a79c..2d35db9f15 100644
--- a/frontend/src/components/data-table/column-formatting/feature.ts
+++ b/frontend/src/components/data-table/column-formatting/feature.ts
@@ -16,6 +16,7 @@ import {
prettyNumber,
prettyScientificNumber,
} from "@/utils/numbers";
+import { memoizeLastValue } from "@/utils/once";
import type {
ColumnFormattingOptions,
ColumnFormattingState,
@@ -39,6 +40,7 @@ export const ColumnFormattingFeature: TableFeature = {
return {
enableColumnFormatting: true,
onColumnFormattingChange: makeStateUpdater("columnFormatting", table),
+ locale: navigator.language,
} as ColumnFormattingOptions;
},
@@ -74,36 +76,50 @@ export const ColumnFormattingFeature: TableFeature = {
const dataType = column.columnDef.meta?.dataType;
const format = column.getColumnFormatting?.();
if (format) {
- return applyFormat(value, { format, dataType });
+ return applyFormat(value, {
+ format,
+ dataType,
+ locale: table.options.locale,
+ });
}
return value;
};
},
};
-const percentFormatter = new Intl.NumberFormat(undefined, {
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2,
-});
+export const getFormatters = memoizeLastValue((locale: string) => {
+ const percentFormatter = new Intl.NumberFormat(locale, {
+ style: "percent",
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 2,
+ });
-const dateFormatter = new Intl.DateTimeFormat(undefined, {
- dateStyle: "short", // 3/4/2024
-});
+ const dateFormatter = new Intl.DateTimeFormat(locale, {
+ dateStyle: "short", // 3/4/2024
+ });
-const dateTimeFormatter = new Intl.DateTimeFormat(undefined, {
- dateStyle: "short", // 3/4/2024
- timeStyle: "long", // 3:04:05 PM
- timeZone: "UTC",
-});
+ const dateTimeFormatter = new Intl.DateTimeFormat(locale, {
+ dateStyle: "short", // 3/4/2024
+ timeStyle: "long", // 3:04:05 PM
+ timeZone: "UTC",
+ });
-const timeFormatter = new Intl.DateTimeFormat(undefined, {
- timeStyle: "long", // 3:04:05 PM
- timeZone: "UTC",
-});
+ const timeFormatter = new Intl.DateTimeFormat(locale, {
+ timeStyle: "long", // 3:04:05 PM
+ timeZone: "UTC",
+ });
-const integerFormatter = new Intl.NumberFormat(undefined, {
- maximumFractionDigits: 0, // 1,000,000
+ const integerFormatter = new Intl.NumberFormat(locale, {
+ maximumFractionDigits: 0, // 1,000,000
+ });
+
+ return {
+ percentFormatter,
+ dateFormatter,
+ dateTimeFormatter,
+ timeFormatter,
+ integerFormatter,
+ };
});
// Apply formatting to a value given a format and data type
@@ -112,9 +128,18 @@ export const applyFormat = (
options: {
format: FormatOption;
dataType: DataType | undefined;
+ locale: string;
},
) => {
- const { format, dataType } = options;
+ const { format, dataType, locale } = options;
+ const {
+ percentFormatter,
+ dateFormatter,
+ dateTimeFormatter,
+ timeFormatter,
+ integerFormatter,
+ } = getFormatters(locale);
+
// If the value is null, return an empty string
if (value === null || value === undefined || value === "") {
return "";
@@ -143,13 +168,13 @@ export const applyFormat = (
const num = Number.parseFloat(value as string);
switch (format) {
case "Auto":
- return prettyNumber(num);
+ return prettyNumber(num, locale);
case "Percent":
return percentFormatter.format(num);
case "Scientific":
- return prettyScientificNumber(num, { shouldRound: true });
+ return prettyScientificNumber(num, { shouldRound: true, locale });
case "Engineering":
- return prettyEngineeringNumber(num);
+ return prettyEngineeringNumber(num, locale);
case "Integer":
return integerFormatter.format(num);
default:
@@ -198,32 +223,35 @@ export const applyFormat = (
export function formattingExample(
format: FormatOption,
+ locale: string,
): string | number | undefined | null {
switch (format) {
case "Date":
return String(
- applyFormat(new Date(), { format: "Date", dataType: "date" }),
+ applyFormat(new Date(), { format: "Date", dataType: "date", locale }),
);
case "Datetime":
return String(
applyFormat(new Date(), {
format: "Datetime",
dataType: "date",
+ locale,
}),
);
case "Time":
return String(
- applyFormat(new Date(), { format: "Time", dataType: "date" }),
+ applyFormat(new Date(), { format: "Time", dataType: "date", locale }),
);
case "Percent":
return String(
- applyFormat(0.1234, { format: "Percent", dataType: "number" }),
+ applyFormat(0.1234, { format: "Percent", dataType: "number", locale }),
);
case "Scientific":
return String(
applyFormat(12_345_678_910, {
format: "Scientific",
dataType: "number",
+ locale,
}),
);
case "Engineering":
@@ -231,15 +259,20 @@ export function formattingExample(
applyFormat(12_345_678_910, {
format: "Engineering",
dataType: "number",
+ locale,
}),
);
case "Integer":
return String(
- applyFormat(1234.567, { format: "Integer", dataType: "number" }),
+ applyFormat(1234.567, {
+ format: "Integer",
+ dataType: "number",
+ locale,
+ }),
);
case "Auto":
return String(
- applyFormat(1234.567, { format: "Auto", dataType: "number" }),
+ applyFormat(1234.567, { format: "Auto", dataType: "number", locale }),
);
default:
return null;
diff --git a/frontend/src/components/data-table/column-formatting/types.ts b/frontend/src/components/data-table/column-formatting/types.ts
index dd6a49c993..a7a5ad7764 100644
--- a/frontend/src/components/data-table/column-formatting/types.ts
+++ b/frontend/src/components/data-table/column-formatting/types.ts
@@ -28,6 +28,7 @@ export interface ColumnFormattingTableState {
// define types for column formatting's table options
export interface ColumnFormattingOptions {
+ locale: string;
enableColumnFormatting?: boolean;
onColumnFormattingChange?: OnChangeFn<ColumnFormattingState>;
}
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsx
index d4132b3c1a..d95072652a 100644
--- a/frontend/src/components/data-table/column-header.tsx
+++ b/frontend/src/components/data-table/column-header.tsx
@@ -5,6 +5,7 @@ import type { Column } from "@tanstack/react-table";
import { capitalize } from "lodash-es";
import { FilterIcon, MinusIcon, TextIcon, XIcon } from "lucide-react";
import { useMemo, useRef, useState } from "react";
+import { useLocale } from "react-aria";
import {
DropdownMenu,
DropdownMenuContent,
@@ -76,6 +77,7 @@ export const DataTableColumnHeader = <TData, TValue>({
calculateTopKRows,
}: DataTableColumnHeaderProps<TData, TValue>) => {
const [isFilterValueOpen, setIsFilterValueOpen] = useState(false);
+ const { locale } = useLocale();
// No header
if (!header) {
@@ -119,7 +121,7 @@ export const DataTableColumnHeader = <TData, TValue>({
{renderCopyColumn(column)}
{renderColumnPinning(column)}
{renderColumnWrapping(column)}
- {renderFormatOptions(column)}
+ {renderFormatOptions(column, locale)}
<DropdownMenuSeparator />
{renderMenuItemFilter(column)}
{renderFilterByValues(column, setIsFilterValueOpen)}
diff --git a/frontend/src/components/data-table/column-summary/column-summary.tsx b/frontend/src/components/data-table/column-summary/column-summary.tsx
index 9c9e2c2c19..d8a5abbd79 100644
--- a/frontend/src/components/data-table/column-summary/column-summary.tsx
+++ b/frontend/src/components/data-table/column-summary/column-summary.tsx
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import React, { Suspense } from "react";
+import { useLocale } from "react-aria";
import { createBatchedLoader } from "@/plugins/impl/vega/batched";
import { useTheme } from "@/theme/useTheme";
import { logNever } from "@/utils/assertNever";
@@ -29,6 +30,8 @@ const batchedLoader = createBatchedLoader();
export const TableColumnSummary = <TData, TValue>({
columnId,
}: Props<TData, TValue>) => {
+ const { locale } = useLocale();
+
const chartSpecModel = React.use(ColumnChartContext);
const { theme } = useTheme();
const { spec, type, stats } = chartSpecModel.getHeaderSummary(columnId);
@@ -65,7 +68,7 @@ export const TableColumnSummary = <TData, TValue>({
) => {
return (
<DatePopover date={date} type={type}>
- {prettyDate(date, type)}
+ {prettyDate(date, type, locale)}
</DatePopover>
);
};
@@ -84,7 +87,7 @@ export const TableColumnSummary = <TData, TValue>({
<div className="flex flex-col whitespace-pre">
<span>min: {renderDate(stats.min, type)}</span>
<span>max: {renderDate(stats.max, type)}</span>
- <span>unique: {prettyNumber(stats.unique)}</span>
+ <span>unique: {prettyNumber(stats.unique, locale)}</span>
</div>
);
}
@@ -106,16 +109,22 @@ export const TableColumnSummary = <TData, TValue>({
<span>
min:{" "}
{typeof stats.min === "number"
- ? prettyScientificNumber(stats.min, { shouldRound: true })
+ ? prettyScientificNumber(stats.min, {
+ shouldRound: true,
+ locale,
+ })
: stats.min}
</span>
<span>
max:{" "}
{typeof stats.max === "number"
- ? prettyScientificNumber(stats.max, { shouldRound: true })
+ ? prettyScientificNumber(stats.max, {
+ shouldRound: true,
+ locale,
+ })
: stats.max}
</span>
- <span>unique: {prettyNumber(stats.unique)}</span>
+ <span>unique: {prettyNumber(stats.unique, locale)}</span>
</div>
);
}
@@ -127,8 +136,8 @@ export const TableColumnSummary = <TData, TValue>({
if (!spec) {
return (
<div className="flex flex-col whitespace-pre">
- <span>true: {prettyNumber(stats.true)}</span>
- <span>false: {prettyNumber(stats.false)}</span>
+ <span>true: {prettyNumber(stats.true, locale)}</span>
+ <span>false: {prettyNumber(stats.false, locale)}</span>
</div>
);
}
@@ -140,7 +149,7 @@ export const TableColumnSummary = <TData, TValue>({
if (!spec) {
return (
<div className="flex flex-col whitespace-pre">
- <span>unique: {prettyNumber(stats.unique)}</span>
+ <span>unique: {prettyNumber(stats.unique, locale)}</span>
</div>
);
}
@@ -148,7 +157,7 @@ export const TableColumnSummary = <TData, TValue>({
case "unknown":
return (
<div className="flex flex-col whitespace-pre">
- <span>nulls: {prettyNumber(stats.nulls)}</span>
+ <span>nulls: {prettyNumber(stats.nulls, locale)}</span>
</div>
);
default:
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index f53fc113d8..baabd0970f 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -4,6 +4,7 @@
import { PopoverClose } from "@radix-ui/react-popover";
import type { Column, ColumnDef } from "@tanstack/react-table";
import { formatDate } from "date-fns";
+import { WithLocale } from "@/core/i18n/with-locale";
import type { DataType } from "@/core/kernel/messages";
import type { CalculateTopKRows } from "@/plugins/impl/DataTablePlugin";
import { cn } from "@/utils/cn";
@@ -227,13 +228,13 @@ export function generateColumns<T>({
isCellSelected,
);
- const renderedCell = renderCellValue(
+ const renderedCell = renderCellValue({
column,
renderValue,
getValue,
selectCell,
cellStyles,
- );
+ });
// Row headers are bold
if (rowHeadersSet.has(key)) {
@@ -403,18 +404,25 @@ function renderAny(value: unknown): string {
}
}
-function renderDate(
- value: Date,
- dataType?: DataType,
- dtype?: string,
- format?: DateFormat | null,
-): React.ReactNode {
+function renderDate({
+ value,
+ dataType,
+ dtype,
+ format,
+ locale,
+}: {
+ value: Date;
+ dataType?: DataType;
+ dtype?: string;
+ format?: DateFormat | null;
+ locale: string;
+}): React.ReactNode {
const type = dataType === "date" ? "date" : "datetime";
const timezone = extractTimezone(dtype);
const exactValue = format
? formatDate(value, format)
- : exactDateTime(value, timezone);
+ : exactDateTime(value, timezone, locale);
return (
<DatePopover date={value} type={type}>
@@ -423,13 +431,19 @@ function renderDate(
);
}
-export function renderCellValue<TData, TValue>(
- column: Column<TData, TValue>,
- renderValue: () => TValue | null,
- getValue: () => TValue,
- selectCell?: () => void,
- cellStyles?: string,
-) {
+export function renderCellValue<TData, TValue>({
+ column,
+ renderValue,
+ getValue,
+ selectCell,
+ cellStyles,
+}: {
+ column: Column<TData, TValue>;
+ renderValue: () => TValue | null;
+ getValue: () => TValue;
+ selectCell?: () => void;
+ cellStyles?: string;
+}) {
const value = getValue();
const format = column.getColumnFormatting?.();
@@ -440,7 +454,13 @@ export function renderCellValue<TData, TValue>(
try {
const date = new Date(value);
const format = getDateFormat(value);
- return renderDate(date, dataType, dtype, format);
+ return (
+ <WithLocale>
+ {(locale) =>
+ renderDate({ value: date, dataType, dtype, format, locale })
+ }
+ </WithLocale>
+ );
} catch (error) {
Logger.error("Error parsing datetime, fallback to string", error);
}
@@ -448,7 +468,11 @@ export function renderCellValue<TData, TValue>(
if (value instanceof Date) {
// e.g. 2010-10-07 17:15:00
- return renderDate(value, dataType, dtype);
+ return (
+ <WithLocale>
+ {(locale) => renderDate({ value, dataType, dtype, locale })}
+ </WithLocale>
+ );
}
if (typeof value === "string") {
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index dc2c0e38a9..c7b7fc4466 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -19,6 +19,7 @@ import {
useReactTable,
} from "@tanstack/react-table";
import React, { memo } from "react";
+import { useLocale } from "react-aria";
import { Table } from "@/components/ui/table";
import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";
@@ -131,6 +132,7 @@ const DataTableInternal = <TData,>({
}: DataTableProps<TData>) => {
const [isSearchEnabled, setIsSearchEnabled] = React.useState<boolean>(false);
const [showLoadingBar, setShowLoadingBar] = React.useState<boolean>(false);
+ const { locale } = useLocale();
const { columnPinning, setColumnPinning } = useColumnPinning(
freezeColumnsLeft,
@@ -199,6 +201,7 @@ const DataTableInternal = <TData,>({
},
}
: {}),
+ locale: locale,
manualPagination: manualPagination,
getPaginationRowModel: getPaginationRowModel(),
// sorting
diff --git a/frontend/src/components/data-table/date-popover.tsx b/frontend/src/components/data-table/date-popover.tsx
index 73c19f432b..e50ce4c33c 100644
--- a/frontend/src/components/data-table/date-popover.tsx
+++ b/frontend/src/components/data-table/date-popover.tsx
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import React from "react";
+import { useDateFormatter, useLocale } from "react-aria";
import { Tooltip } from "@/components/ui/tooltip";
interface DatePopoverProps {
@@ -19,33 +20,17 @@ export const DatePopover: React.FC<DatePopoverProps> = ({
}
const dateObj = new Date(date);
- const relativeTime = getRelativeTime(dateObj);
const content = (
<div className="min-w-[240px] p-1 text-sm">
- <div className="text-muted-foreground mb-2">{relativeTime}</div>
+ <div className="text-muted-foreground mb-2">
+ <RelativeTime date={dateObj} />
+ </div>
<div className="space-y-1">
{type === "datetime" ? (
- Object.entries(getTimezones(dateObj)).map(
- ([timezone, formattedDate]) => (
- <div
- key={timezone}
- className="grid grid-cols-[fit-content(40px)_1fr] gap-4 items-center justify-items-end"
- >
- <span className="bg-muted rounded-md py-1 px-2 w-fit ml-auto">
- {timezone}
- </span>
- <span>{formattedDate}</span>
- </div>
- ),
- )
+ <TimezoneDisplay date={dateObj} />
) : (
- <span>
- {dateObj.toLocaleDateString("en-US", {
- timeZone: "UTC",
- dateStyle: "long",
- })}
- </span>
+ <DateDisplay date={dateObj} />
)}
</div>
</div>
@@ -58,57 +43,79 @@ export const DatePopover: React.FC<DatePopoverProps> = ({
);
};
-function getTimezones(date: Date) {
- const localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
-
+const TimezoneDisplay = ({ date }: { date: Date }) => {
+ const { locale } = useLocale();
+ const localTimezone = Intl.DateTimeFormat(locale).resolvedOptions().timeZone;
const hasSubSeconds = date.getUTCMilliseconds() !== 0;
- if (hasSubSeconds) {
- return {
- UTC: new Intl.DateTimeFormat("en-US", {
- timeZone: "UTC",
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- fractionalSecondDigits: 3,
- }).format(date),
- [localTimezone]: new Intl.DateTimeFormat("en-US", {
- timeZone: localTimezone,
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- fractionalSecondDigits: 3,
- }).format(date),
- };
- }
- return {
- UTC: new Intl.DateTimeFormat("en-US", {
- timeZone: "UTC",
- dateStyle: "long",
- timeStyle: "medium",
- }).format(date),
- [localTimezone]: new Intl.DateTimeFormat("en-US", {
- timeZone: localTimezone,
- dateStyle: "long",
- timeStyle: "medium",
- }).format(date),
- };
-}
+ const utcFormatter = useDateFormatter(
+ hasSubSeconds
+ ? {
+ timeZone: "UTC",
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ fractionalSecondDigits: 3,
+ }
+ : {
+ timeZone: "UTC",
+ dateStyle: "long",
+ timeStyle: "medium",
+ },
+ );
+
+ const localFormatter = useDateFormatter(
+ hasSubSeconds
+ ? {
+ timeZone: localTimezone,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ fractionalSecondDigits: 3,
+ }
+ : {
+ timeZone: localTimezone,
+ dateStyle: "long",
+ timeStyle: "medium",
+ },
+ );
+
+ return (
+ <>
+ <div className="grid grid-cols-[fit-content(40px)_1fr] gap-4 items-center justify-items-end">
+ <span className="bg-muted rounded-md py-1 px-2 w-fit ml-auto">UTC</span>
+ <span>{utcFormatter.format(date)}</span>
+ </div>
+ <div className="grid grid-cols-[fit-content(40px)_1fr] gap-4 items-center justify-items-end">
+ <span className="bg-muted rounded-md py-1 px-2 w-fit ml-auto">
+ {localTimezone}
+ </span>
+ <span>{localFormatter.format(date)}</span>
+ </div>
+ </>
+ );
+};
+
+const DateDisplay = ({ date }: { date: Date }) => {
+ const dateFormatter = useDateFormatter({
+ timeZone: "UTC",
+ dateStyle: "long",
+ });
-/**
- * Converts a date into a human-readable relative time string (e.g. "2 hours ago", "in 5 minutes")
- * Uses Intl.RelativeTimeFormat for localized formatting
- */
-function getRelativeTime(date: Date): string {
- // Initialize relative time formatter with English locale and "auto" numeric style
- // "auto" allows for strings like "yesterday" instead of "1 day ago"
- const relativeTimeFormatter = new Intl.RelativeTimeFormat("en", {
+ return <span>{dateFormatter.format(date)}</span>;
+};
+
+const RelativeTime = ({ date }: { date: Date }) => {
+ const { locale } = useLocale();
+
+ // Initialize relative time formatter with current locale and "auto" numeric style
+ const relativeTimeFormatter = new Intl.RelativeTimeFormat(locale, {
numeric: "auto",
});
@@ -117,7 +124,6 @@ function getRelativeTime(date: Date): string {
const differenceInSeconds = (currentTime.getTime() - date.getTime()) / 1000;
// Define time units with their thresholds and conversion factors
- // Format: [threshold before next unit, seconds in this unit, unit name]
const timeUnits: Array<[number, number, string]> = [
[60, 1, "second"], // Less than 60 seconds
[60, 60, "minute"], // Less than 60 minutes
@@ -134,13 +140,17 @@ function getRelativeTime(date: Date): string {
// Convert to fixed decimal and negate since RelativeTimeFormat expects
// negative values for past times and positive for future times
const roundedValue = -Number(valueInUnits.toFixed(1));
- return relativeTimeFormatter.format(
- roundedValue,
- unitName as Intl.RelativeTimeFormatUnit,
+ return (
+ <span>
+ {relativeTimeFormatter.format(
+ roundedValue,
+ unitName as Intl.RelativeTimeFormatUnit,
+ )}
+ </span>
);
}
}
// Should never reach here due to Infinity threshold, but provide fallback
- return relativeTimeFormatter.format(0, "second");
-}
+ return <span>{relativeTimeFormatter.format(0, "second")}</span>;
+};
diff --git a/frontend/src/components/data-table/filter-pills.tsx b/frontend/src/components/data-table/filter-pills.tsx
index 3a8cd68d4a..6680c97898 100644
--- a/frontend/src/components/data-table/filter-pills.tsx
+++ b/frontend/src/components/data-table/filter-pills.tsx
@@ -7,6 +7,7 @@ import type {
Table,
} from "@tanstack/react-table";
import { XIcon } from "lucide-react";
+import { type DateFormatter, useDateFormatter } from "react-aria";
import { logNever } from "@/utils/assertNever";
import { Badge } from "../ui/badge";
import type { ColumnFilterValue } from "./filters";
@@ -18,12 +19,21 @@ interface Props<TData> {
}
export const FilterPills = <TData,>({ filters, table }: Props<TData>) => {
+ const timeFormatter = useDateFormatter({
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
+
if (!filters || filters.length === 0) {
return null;
}
function renderFilterPill(filter: ColumnFilter) {
- const formattedValue = formatValue(filter.value as ColumnFilterValue);
+ const formattedValue = formatValue(
+ filter.value as ColumnFilterValue,
+ timeFormatter,
+ );
if (!formattedValue) {
return null;
}
@@ -52,7 +62,7 @@ export const FilterPills = <TData,>({ filters, table }: Props<TData>) => {
);
};
-function formatValue(value: ColumnFilterValue) {
+function formatValue(value: ColumnFilterValue, timeFormatter: DateFormatter) {
if (!("type" in value)) {
return;
}
@@ -71,14 +81,9 @@ function formatValue(value: ColumnFilterValue) {
return formatMinMax(value.min?.toISOString(), value.max?.toISOString());
}
if (value.type === "time") {
- const formatTime = new Intl.DateTimeFormat("en-US", {
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- });
return formatMinMax(
- value.min ? formatTime.format(value.min) : undefined,
- value.max ? formatTime.format(value.max) : undefined,
+ value.min ? timeFormatter.format(value.min) : undefined,
+ value.max ? timeFormatter.format(value.max) : undefined,
);
}
if (value.type === "datetime") {
diff --git a/frontend/src/components/data-table/header-items.tsx b/frontend/src/components/data-table/header-items.tsx
index 0b69b9865f..500e527036 100644
--- a/frontend/src/components/data-table/header-items.tsx
+++ b/frontend/src/components/data-table/header-items.tsx
@@ -34,6 +34,7 @@ import { NAMELESS_COLUMN_PREFIX } from "./columns";
export function renderFormatOptions<TData, TValue>(
column: Column<TData, TValue>,
+ locale: string,
) {
const dataType: DataType | undefined = column.columnDef.meta?.dataType;
const columnFormatOptions = dataType ? formatOptions[dataType] : [];
@@ -51,6 +52,9 @@ export function renderFormatOptions<TData, TValue>(
</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent>
+ <div className="text-xs text-muted-foreground px-2 py-1">
+ Locale: {locale}
+ </div>
{Boolean(currentFormat) && (
<>
<DropdownMenuItem
@@ -72,7 +76,7 @@ export function renderFormatOptions<TData, TValue>(
{option}
</span>
<span className="ml-auto pl-5 text-xs text-muted-foreground">
- {formattingExample(option)}
+ {formattingExample(option, locale)}
</span>
</DropdownMenuItem>
))}
diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsx
index 730ecbb72b..4cd4691b92 100644
--- a/frontend/src/components/data-table/pagination.tsx
+++ b/frontend/src/components/data-table/pagination.tsx
@@ -9,8 +9,10 @@ import {
ChevronsLeft,
ChevronsRight,
} from "lucide-react";
+import { useLocale } from "react-aria";
import { Button } from "@/components/ui/button";
import { Events } from "@/utils/events";
+import { prettyNumber } from "@/utils/numbers";
import { PluralWord } from "@/utils/pluralize";
import {
Select,
@@ -40,6 +42,8 @@ export const DataTablePagination = <TData,>({
tableLoading,
showPageSizeSelector,
}: DataTablePaginationProps<TData>) => {
+ const { locale } = useLocale();
+
const renderTotal = () => {
const { rowSelection, cellSelection } = table.getState();
let selected = Object.keys(rowSelection).length;
@@ -58,7 +62,7 @@ export const DataTablePagination = <TData,>({
if (isAllPageSelected && !isAllSelected) {
return (
<>
- <span>{prettyNumber(selected)} selected</span>
+ <span>{prettyNumber(selected, locale)} selected</span>
<Button
size="xs"
data-testid="select-all-button"
@@ -73,7 +77,7 @@ export const DataTablePagination = <TData,>({
}
}}
>
- Select all {prettyNumber(numRows)}
+ Select all {prettyNumber(numRows, locale)}
</Button>
</>
);
@@ -82,7 +86,7 @@ export const DataTablePagination = <TData,>({
if (selected) {
return (
<>
- <span>{prettyNumber(selected)} selected</span>
+ <span>{prettyNumber(selected, locale)} selected</span>
<Button
size="xs"
data-testid="clear-selection-button"
@@ -107,7 +111,11 @@ export const DataTablePagination = <TData,>({
);
}
- const rowColumnCount = prettifyRowColumnCount(numRows, totalColumns);
+ const rowColumnCount = prettifyRowColumnCount(
+ numRows,
+ totalColumns,
+ locale,
+ );
return <span>{rowColumnCount}</span>;
};
const currentPage = Math.min(
@@ -199,7 +207,9 @@ export const DataTablePagination = <TData,>({
handlePageChange(() => table.setPageIndex(page))
}
/>
- <span className="shrink-0">of {prettyNumber(totalPages)}</span>
+ <span className="shrink-0">
+ of {prettyNumber(totalPages, locale)}
+ </span>
</div>
<Button
size="xs"
@@ -232,10 +242,6 @@ export const DataTablePagination = <TData,>({
);
};
-function prettyNumber(value: number): string {
- return new Intl.NumberFormat().format(value);
-}
-
export const PageSelector = ({
currentPage,
totalPages,
@@ -313,17 +319,18 @@ export const PageSelector = ({
);
};
-export function prettifyRowCount(rowCount: number): string {
- return `${prettyNumber(rowCount)} ${new PluralWord("row").pluralize(rowCount)}`;
+export function prettifyRowCount(rowCount: number, locale: string): string {
+ return `${prettyNumber(rowCount, locale)} ${new PluralWord("row").pluralize(rowCount)}`;
}
export const prettifyRowColumnCount = (
numRows: number | "too_many",
totalColumns: number,
+ locale: string,
): string => {
const rowsLabel =
- numRows === "too_many" ? "Unknown" : prettifyRowCount(numRows);
- const columnsLabel = `${prettyNumber(totalColumns)} ${new PluralWord("column").pluralize(totalColumns)}`;
+ numRows === "too_many" ? "Unknown" : prettifyRowCount(numRows, locale);
+ const columnsLabel = `${prettyNumber(totalColumns, locale)} ${new PluralWord("column").pluralize(totalColumns)}`;
return [rowsLabel, columnsLabel].join(", ");
};
diff --git a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
index 01fda8f3cd..e3aed00206 100644
--- a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
+++ b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
@@ -15,6 +15,7 @@ import {
SearchIcon,
} from "lucide-react";
import { useRef, useState } from "react";
+import { useLocale } from "react-aria";
import { ColumnName } from "@/components/datasources/components";
import { CopyClipboardIcon } from "@/components/icons/copy-icon";
import { KeyboardHotkeys } from "@/components/shortcuts/renderShortcut";
@@ -66,6 +67,7 @@ export const RowViewerPanel: React.FC<RowViewerPanelProps> = ({
const [searchQuery, setSearchQuery] = useState("");
const panelRef = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
+ const { locale } = useLocale();
const tooManyRows = totalRows === TOO_MANY_ROWS;
@@ -204,13 +206,13 @@ export const RowViewerPanel: React.FC<RowViewerPanelProps> = ({
applyColumnFormatting: (value) => value,
} as Column<unknown>;
- const cellContent = renderCellValue(
- mockColumn,
- () => columnValue,
- () => columnValue,
- undefined,
- "text-left break-word",
- );
+ const cellContent = renderCellValue({
+ column: mockColumn,
+ renderValue: () => columnValue,
+ getValue: () => columnValue,
+ selectCell: undefined,
+ cellStyles: "text-left break-word",
+ });
const copyValue =
typeof columnValue === "object"
@@ -286,7 +288,7 @@ export const RowViewerPanel: React.FC<RowViewerPanelProps> = ({
<span className="text-xs">
{tooManyRows
? `Row ${rowIdx + 1}`
- : `Row ${rowIdx + 1} of ${prettifyRowCount(totalRows)}`}
+ : `Row ${rowIdx + 1} of ${prettifyRowCount(totalRows, locale)}`}
</span>
<Button
variant="outline"
diff --git a/frontend/src/components/datasources/column-preview.tsx b/frontend/src/components/datasources/column-preview.tsx
index 4ef6837076..0983e36883 100644
--- a/frontend/src/components/datasources/column-preview.tsx
+++ b/frontend/src/components/datasources/column-preview.tsx
@@ -3,6 +3,7 @@
import { useAtomValue } from "jotai";
import { PlusSquareIcon } from "lucide-react";
import React, { Suspense } from "react";
+import { useLocale } from "react-aria";
import { maybeAddAltairImport } from "@/core/cells/add-missing-import";
import { useCellActions } from "@/core/cells/cells";
import { useLastFocusedCellId } from "@/core/cells/focus";
@@ -42,6 +43,7 @@ export const DatasetColumnPreview: React.FC<{
}> = ({ table, column, preview, onAddColumnChart, sqlTableContext }) => {
const { theme } = useTheme();
const { previewDatasetColumn } = useRequestClient();
+ const { locale } = useLocale();
const previewColumn = () => {
previewDatasetColumn({
@@ -107,7 +109,8 @@ export const DatasetColumnPreview: React.FC<{
refetchPreview: previewColumn,
});
- const stats = preview.stats && renderStats(preview.stats, column.type);
+ const stats =
+ preview.stats && renderStats(preview.stats, column.type, locale);
const chart = preview.chart_spec && renderChart(preview.chart_spec, theme);
@@ -175,6 +178,7 @@ export function renderPreviewError({
export function renderStats(
stats: Partial<Record<ColumnHeaderStatsKey, unknown>>,
dataType: DataType,
+ locale: string,
) {
return (
<div className="gap-x-16 gap-y-1 grid grid-cols-2-fit border rounded p-2 empty:hidden">
@@ -189,7 +193,7 @@ export function renderStats(
{convertStatsName(key as ColumnHeaderStatsKey, dataType)}
</span>
<span className="text-xs font-bold text-muted-foreground tracking-wide">
- {prettyNumber(value)}
+ {prettyNumber(value, locale)}
</span>
<CopyClipboardIcon
className="h-3 w-3 invisible group-hover:visible"
diff --git a/frontend/src/components/editor/cell/CellStatus.tsx b/frontend/src/components/editor/cell/CellStatus.tsx
index 2a8b230a71..d123a65acf 100644
--- a/frontend/src/components/editor/cell/CellStatus.tsx
+++ b/frontend/src/components/editor/cell/CellStatus.tsx
@@ -5,6 +5,7 @@ import {
RefreshCwIcon,
WorkflowIcon,
} from "lucide-react";
+import { useDateFormatter } from "react-aria";
import { MultiIcon } from "@/components/icons/multi-icon";
import { Logger } from "@/utils/Logger";
import type { CellRuntimeState } from "../../../core/cells/types";
@@ -28,26 +29,6 @@ export interface CellStatusComponentProps
uninstantiated: boolean;
}
-// Looks like HH:MM:SS.SSS AM/PM
-const timeFormatter = new Intl.DateTimeFormat("en-US", {
- hour: "numeric",
- minute: "numeric",
- second: "numeric",
- fractionalSecondDigits: 3,
- hour12: true,
-});
-
-// Looks like MM/DD HH:MM:SS.SSS AM/PM
-const dateTimeFormatter = new Intl.DateTimeFormat("en-US", {
- month: "numeric",
- day: "numeric",
- hour: "numeric",
- minute: "numeric",
- second: "numeric",
- fractionalSecondDigits: 3,
- hour12: true,
-});
-
export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({
editing,
status,
@@ -329,10 +310,32 @@ export const ElapsedTime = (props: { elapsedTime: string }) => {
const LastRanTime = (props: { lastRanTime: number }) => {
const date = new Date(props.lastRanTime * 1000);
const today = new Date();
+
+ // Looks like HH:MM:SS.SSS AM/PM
+ const timeFormatter = useDateFormatter({
+ hour: "numeric",
+ minute: "numeric",
+ second: "numeric",
+ fractionalSecondDigits: 3,
+ hour12: true,
+ });
+
+ // Looks like MM/DD HH:MM:SS.SSS AM/PM
+ const dateTimeFormatter = useDateFormatter({
+ month: "numeric",
+ day: "numeric",
+ hour: "numeric",
+ minute: "numeric",
+ second: "numeric",
+ fractionalSecondDigits: 3,
+ hour12: true,
+ });
+
const formatter =
date.toDateString() === today.toDateString()
? timeFormatter
: dateTimeFormatter;
+
return (
<span>
Ran at{" "}
diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/machine-stats.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/machine-stats.tsx
index c00eff844e..2b3a0bf8c9 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer-items/machine-stats.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/machine-stats.tsx
@@ -4,6 +4,7 @@ import { useAtomValue } from "jotai";
import { CpuIcon, MemoryStickIcon, MicrochipIcon } from "lucide-react";
import type React from "react";
import { useState } from "react";
+import { useNumberFormatter } from "react-aria";
import { Tooltip } from "@/components/ui/tooltip";
import { connectionAtom } from "@/core/network/connection";
import { useRequestClient } from "@/core/network/requests";
@@ -56,23 +57,42 @@ const MemoryUsageBar: React.FC<{
}> = ({ memory, kernel, server }) => {
const { percent, total, available } = memory;
const roundedPercent = Math.round(percent);
+
+ const gbFormatter = useNumberFormatter({
+ maximumFractionDigits: 2,
+ });
+ const mbFormatter = useNumberFormatter({
+ maximumFractionDigits: 0,
+ });
+
+ const formatBytes = (bytes: number): string => {
+ if (bytes > 1024 * 1024 * 1024) {
+ return `${gbFormatter.format(bytes / (1024 * 1024 * 1024))} GB`;
+ }
+ return `${mbFormatter.format(bytes / (1024 * 1024))} MB`;
+ };
+
+ const formatGB = (bytes: number): string => {
+ return gbFormatter.format(bytes / (1024 * 1024 * 1024));
+ };
+
return (
<Tooltip
delayDuration={200}
content={
<div className="flex flex-col gap-1">
<span>
- <b>computer memory:</b> {asGB(total - available)} / {asGB(total)} GB
- ({roundedPercent}%)
+ <b>computer memory:</b> {formatGB(total - available)} /{" "}
+ {formatGB(total)} GB ({roundedPercent}%)
</span>
{server?.memory && (
<span>
- <b>marimo server:</b> {asGBorMB(server.memory)}
+ <b>marimo server:</b> {formatBytes(server.memory)}
</span>
)}
{kernel?.memory && (
<span>
- <b>kernel:</b> {asGBorMB(kernel.memory)}
+ <b>kernel:</b> {formatBytes(kernel.memory)}
</span>
)}
</div>
@@ -122,6 +142,20 @@ const GPUBar: React.FC<{ gpus: GPU[] }> = ({ gpus }) => {
gpus.length,
);
+ const gbFormatter = useNumberFormatter({
+ maximumFractionDigits: 2,
+ });
+ const mbFormatter = useNumberFormatter({
+ maximumFractionDigits: 0,
+ });
+
+ const formatBytes = (bytes: number): string => {
+ if (bytes > 1024 * 1024 * 1024) {
+ return `${gbFormatter.format(bytes / (1024 * 1024 * 1024))} GB`;
+ }
+ return `${mbFormatter.format(bytes / (1024 * 1024))} MB`;
+ };
+
return (
<Tooltip
delayDuration={200}
@@ -132,7 +166,7 @@ const GPUBar: React.FC<{ gpus: GPU[] }> = ({ gpus }) => {
<b>
GPU {gpu.index} ({gpu.name}):
</b>{" "}
- {asGBorMB(gpu.memory.used)} / {asGBorMB(gpu.memory.total)} GB (
+ {formatBytes(gpu.memory.used)} / {formatBytes(gpu.memory.total)} (
{Math.round(gpu.memory.percent)}%)
</span>
))}
@@ -160,26 +194,3 @@ const Bar: React.FC<{ percent: number; colorClassName?: string }> = ({
</div>
);
};
-
-function asGBorMB(bytes: number): string {
- if (bytes > 1024 * 1024 * 1024) {
- return `${asGB(bytes)} GB`;
- }
- return `${asMB(bytes)} MB`;
-}
-
-function asMB(bytes: number) {
- // 0 decimal places
- const format = new Intl.NumberFormat("en-US", {
- maximumFractionDigits: 0,
- });
- return format.format(bytes / (1024 * 1024));
-}
-
-function asGB(bytes: number) {
- // At most 2 decimal places
- const format = new Intl.NumberFormat("en-US", {
- maximumFractionDigits: 2,
- });
- return format.format(bytes / (1024 * 1024 * 1024));
-}
diff --git a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
index 884cdfd80c..fec9d11a62 100644
--- a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
+++ b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
@@ -2,6 +2,7 @@
import { MenuIcon } from "lucide-react";
import React from "react";
+import { useLocale } from "react-aria";
import { Button } from "@/components/editor/inputs/Inputs";
import {
DropdownMenu,
@@ -33,7 +34,7 @@ export const NotebookMenuDropdown: React.FC<Props> = ({
tooltip = "Actions",
}) => {
const actions = useNotebookActions();
-
+ const { locale } = useLocale();
// Create tooltip content with keyboard shortcut decoration
const tooltipContent = (
<div className="flex flex-col gap-2">
@@ -148,7 +149,8 @@ export const NotebookMenuDropdown: React.FC<Props> = ({
);
})}
<DropdownMenuSeparator />
- <div className="flex-1 px-2 text-xs text-muted-foreground">
+ <div className="flex-1 px-2 text-xs text-muted-foreground flex flex-col gap-1">
+ <span>Locale: {locale}</span>
<span>Version: {getMarimoVersion()}</span>
</div>
</DropdownMenuContent>
diff --git a/frontend/src/components/pages/home-page.tsx b/frontend/src/components/pages/home-page.tsx
index 464abb80a7..631c3585d0 100644
--- a/frontend/src/components/pages/home-page.tsx
+++ b/frontend/src/components/pages/home-page.tsx
@@ -21,6 +21,7 @@ import {
Tree,
type TreeApi,
} from "react-arborist";
+import { useLocale } from "react-aria";
import { MarkdownIcon } from "@/components/editor/cell/code/icons";
import { useImperativeModal } from "@/components/modal/ImperativeModal";
import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";
@@ -383,6 +384,8 @@ const NotebookList: React.FC<{
};
const MarimoFileComponent = ({ file }: { file: MarimoFile }) => {
+ const { locale } = useLocale();
+
// If path is a sessionId, then it has not been saved yet
// We want to keep the sessionId in this case
const isNewNotebook = isSessionId(file.path);
@@ -427,7 +430,7 @@ const MarimoFileComponent = ({ file }: { file: MarimoFile }) => {
</div>
{!!file.lastModified && (
<div className="text-xs text-muted-foreground opacity-80">
- {timeAgo(file.lastModified * 1000)}
+ {timeAgo(file.lastModified * 1000, locale)}
</div>
)}
</div>
diff --git a/frontend/src/components/ui/range-slider.tsx b/frontend/src/components/ui/range-slider.tsx
index a51595e580..48e8cb7dbd 100644
--- a/frontend/src/components/ui/range-slider.tsx
+++ b/frontend/src/components/ui/range-slider.tsx
@@ -3,6 +3,7 @@
import * as SliderPrimitive from "@radix-ui/react-slider";
import { TooltipPortal } from "@radix-ui/react-tooltip";
import * as React from "react";
+import { useLocale } from "react-aria";
import { cn } from "@/utils/cn";
import { prettyScientificNumber } from "@/utils/numbers";
import { useBoolean } from "../../hooks/useBoolean";
@@ -20,6 +21,7 @@ const RangeSlider = React.forwardRef<
}
>(({ className, valueMap, ...props }, ref) => {
const [open, openActions] = useBoolean(false);
+ const { locale } = useLocale();
return (
<SliderPrimitive.Root
@@ -66,7 +68,7 @@ const RangeSlider = React.forwardRef<
<TooltipPortal>
{props.value != null && props.value.length === 2 && (
<TooltipContent key={props.value[0]}>
- {prettyScientificNumber(valueMap(props.value[0]))}
+ {prettyScientificNumber(valueMap(props.value[0]), { locale })}
</TooltipContent>
)}
</TooltipPortal>
@@ -87,7 +89,7 @@ const RangeSlider = React.forwardRef<
<TooltipPortal>
{props.value != null && props.value.length === 2 && (
<TooltipContent key={props.value[1]}>
- {prettyScientificNumber(valueMap(props.value[1]))}
+ {prettyScientificNumber(valueMap(props.value[1]), { locale })}
</TooltipContent>
)}
</TooltipPortal>
diff --git a/frontend/src/components/ui/slider.tsx b/frontend/src/components/ui/slider.tsx
index 2c6d2cf934..ba554e2811 100644
--- a/frontend/src/components/ui/slider.tsx
+++ b/frontend/src/components/ui/slider.tsx
@@ -3,6 +3,7 @@
import * as SliderPrimitive from "@radix-ui/react-slider";
import { TooltipPortal } from "@radix-ui/react-tooltip";
import * as React from "react";
+import { useLocale } from "react-aria";
import { cn } from "@/utils/cn";
import { prettyScientificNumber } from "@/utils/numbers";
import { useBoolean } from "../../hooks/useBoolean";
@@ -20,6 +21,7 @@ const Slider = React.forwardRef<
}
>(({ className, valueMap, ...props }, ref) => {
const [open, openActions] = useBoolean(false);
+ const { locale } = useLocale();
return (
<SliderPrimitive.Root
@@ -66,7 +68,7 @@ const Slider = React.forwardRef<
<TooltipPortal>
{props.value != null && props.value.length === 1 && (
<TooltipContent key={props.value[0]}>
- {prettyScientificNumber(valueMap(props.value[0]))}
+ {prettyScientificNumber(valueMap(props.value[0]), { locale })}
</TooltipContent>
)}
</TooltipPortal>
diff --git a/frontend/src/components/variables/variables-table.tsx b/frontend/src/components/variables/variables-table.tsx
index e61df5231f..47da4edaee 100644
--- a/frontend/src/components/variables/variables-table.tsx
+++ b/frontend/src/components/variables/variables-table.tsx
@@ -14,6 +14,7 @@ import {
import { sortBy } from "lodash-es";
import { SquareEqualIcon, WorkflowIcon } from "lucide-react";
import React, { memo, useMemo } from "react";
+import { useLocale } from "react-aria";
import { CellLink } from "@/components/editor/links/cell-link";
import { getCellEditorView, useCellNames } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
@@ -233,6 +234,7 @@ export const VariableTable: React.FC<Props> = memo(
const [sorting, setSorting] = React.useState<SortingState>([]);
const [globalFilter, setGlobalFilter] = React.useState("");
const cellNames = useCellNames();
+ const { locale } = useLocale();
const resolvedVariables: ResolvedVariable[] = useMemo(() => {
const getName = (id: CellId) => {
@@ -279,6 +281,7 @@ export const VariableTable: React.FC<Props> = memo(
globalFilterFn: "auto",
// sorting
manualSorting: true,
+ locale: locale,
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
state: {
diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsx
index 346d0d38ee..c5851abdc8 100644
--- a/frontend/src/core/MarimoApp.tsx
+++ b/frontend/src/core/MarimoApp.tsx
@@ -15,6 +15,7 @@ import { ErrorBoundary } from "../components/editor/boundary/ErrorBoundary";
import { ModalProvider } from "../components/modal/ImperativeModal";
import { Toaster } from "../components/ui/toaster";
import { TooltipProvider } from "../components/ui/tooltip";
+import { LocaleProvider } from "./i18n/locale-provider";
import { slotsController } from "./slots/slots";
// Force tailwind classnames
@@ -69,7 +70,7 @@ export const MarimoApp: React.FC = memo(() => {
<CssVariables
variables={{ "--marimo-code-editor-font-size": editorFontSize }}
>
- {renderBody()}
+ <LocaleProvider>{renderBody()}</LocaleProvider>
</CssVariables>
</Providers>
);
@@ -85,11 +86,13 @@ const Providers = memo(({ children }: PropsWithChildren) => {
<Suspense>
<TooltipProvider>
<SlotzProvider controller={slotsController}>
- <ModalProvider>
- {children}
- <Toaster />
- <TailwindIndicator />
- </ModalProvider>
+ <LocaleProvider>
+ <ModalProvider>
+ {children}
+ <Toaster />
+ <TailwindIndicator />
+ </ModalProvider>
+ </LocaleProvider>
</SlotzProvider>
</TooltipProvider>
</Suspense>
diff --git a/frontend/src/core/cells/logs.ts b/frontend/src/core/cells/logs.ts
index 41c2fcb422..f67ffbad7e 100644
--- a/frontend/src/core/cells/logs.ts
+++ b/frontend/src/core/cells/logs.ts
@@ -102,7 +102,7 @@ export function formatLogTimestamp(timestamp: number): string {
try {
// parse from UTC
const date = fromUnixTime(timestamp);
- return date.toLocaleTimeString("en-US", {
+ return date.toLocaleTimeString(undefined, {
hour12: true,
hour: "numeric",
minute: "numeric",
diff --git a/frontend/src/core/i18n/__tests__/locale-provider.test.tsx b/frontend/src/core/i18n/__tests__/locale-provider.test.tsx
index 5d01ff202e..4255cd0cdc 100644
--- a/frontend/src/core/i18n/__tests__/locale-provider.test.tsx
+++ b/frontend/src/core/i18n/__tests__/locale-provider.test.tsx
@@ -2,11 +2,23 @@
import { cleanup, render } from "@testing-library/react";
import { createStore, Provider } from "jotai";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { userConfigAtom } from "@/core/config/config";
import { parseUserConfig } from "@/core/config/config-schema";
import { LocaleProvider } from "../locale-provider";
+// Mock navigator.language with a getter
+let mockNavigatorLanguage: string | undefined;
+
+Object.defineProperty(window, "navigator", {
+ value: {
+ get language() {
+ return mockNavigatorLanguage;
+ },
+ },
+ writable: true,
+});
+
// Mock react-aria-components I18nProvider
vi.mock("react-aria-components", () => ({
I18nProvider: ({
@@ -14,7 +26,7 @@ vi.mock("react-aria-components", () => ({
locale,
}: {
children: React.ReactNode;
- locale?: string;
+ locale: string;
}) => (
<div data-testid="i18n-provider" data-locale={locale}>
{children}
@@ -23,8 +35,16 @@ vi.mock("react-aria-components", () => ({
}));
describe("LocaleProvider", () => {
+ beforeEach(() => {
+ // Reset the mock before each test
+ mockNavigatorLanguage = undefined;
+ });
+
afterEach(() => {
cleanup();
+ // Clear all mocks after each test
+ mockNavigatorLanguage = undefined;
+ vi.clearAllMocks();
});
it("should render I18nProvider without locale when locale is null", () => {
@@ -133,6 +153,8 @@ describe("LocaleProvider", () => {
});
it("should auto-detect locale when no locale is set in config", () => {
+ mockNavigatorLanguage = "de-DE";
+
const store = createStore();
const config = parseUserConfig({});
store.set(userConfigAtom, config);
@@ -147,8 +169,8 @@ describe("LocaleProvider", () => {
const i18nProvider = getByTestId("i18n-provider");
expect(i18nProvider).toBeInTheDocument();
- // When no locale is specified in config, it should default to undefined/null
- expect(i18nProvider.dataset.locale).toBe(undefined);
+ // When no locale is specified in config, it should use navigator.language
+ expect(i18nProvider.dataset.locale).toBe("de-DE");
expect(i18nProvider).toHaveTextContent("Test content");
});
});
diff --git a/frontend/src/core/i18n/locale-provider.tsx b/frontend/src/core/i18n/locale-provider.tsx
index e727978142..459a85f126 100644
--- a/frontend/src/core/i18n/locale-provider.tsx
+++ b/frontend/src/core/i18n/locale-provider.tsx
@@ -12,10 +12,24 @@ interface LocaleProviderProps {
export const LocaleProvider = ({ children }: LocaleProviderProps) => {
const locale = useAtomValue(localeAtom);
- // If locale is null or undefined, let React Aria auto-detect
+ return <I18nProvider locale={safeLocale(locale)}>{children}</I18nProvider>;
+};
+
+function safeLocale(locale: string | null | undefined) {
if (!locale) {
- return <I18nProvider>{children}</I18nProvider>;
+ return navigator.language;
}
+ if (isValidLocale(locale)) {
+ return locale;
+ }
+ return navigator.language;
+}
- return <I18nProvider locale={locale}>{children}</I18nProvider>;
-};
+function isValidLocale(locale: string) {
+ try {
+ new Intl.NumberFormat(locale);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/frontend/src/core/i18n/with-locale.tsx b/frontend/src/core/i18n/with-locale.tsx
new file mode 100644
index 0000000000..458b90a39f
--- /dev/null
+++ b/frontend/src/core/i18n/with-locale.tsx
@@ -0,0 +1,12 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useLocale } from "react-aria";
+
+export const WithLocale = ({
+ children,
+}: {
+ children: (locale: string) => React.ReactNode;
+}) => {
+ const { locale } = useLocale();
+ return children(locale);
+};
diff --git a/frontend/src/hooks/useFormatting.ts b/frontend/src/hooks/useFormatting.ts
new file mode 100644
index 0000000000..6ad9facac3
--- /dev/null
+++ b/frontend/src/hooks/useFormatting.ts
@@ -0,0 +1,97 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useCallback } from "react";
+import { useLocale } from "react-aria";
+import { getShortTimeZone, prettyDate, timeAgo } from "@/utils/dates";
+import {
+ prettyEngineeringNumber,
+ prettyNumber,
+ prettyScientificNumber,
+} from "@/utils/numbers";
+
+/**
+ * Hook that provides locale-aware number formatting using the prettyNumber utility
+ */
+export function usePrettyNumber() {
+ const { locale } = useLocale();
+
+ return useCallback(
+ (value: unknown): string => {
+ return prettyNumber(value, locale);
+ },
+ [locale],
+ );
+}
+
+/**
+ * Hook that provides locale-aware scientific number formatting
+ */
+export function usePrettyScientificNumber() {
+ const { locale } = useLocale();
+
+ return useCallback(
+ (value: number, opts: { shouldRound?: boolean } = {}): string => {
+ return prettyScientificNumber(value, { ...opts, locale });
+ },
+ [locale],
+ );
+}
+
+/**
+ * Hook that provides locale-aware engineering number formatting
+ */
+export function usePrettyEngineeringNumber() {
+ const { locale } = useLocale();
+
+ return useCallback(
+ (value: number): string => {
+ return prettyEngineeringNumber(value, locale);
+ },
+ [locale],
+ );
+}
+
+/**
+ * Hook that provides locale-aware date formatting
+ */
+export function usePrettyDate() {
+ const { locale } = useLocale();
+
+ return useCallback(
+ (
+ value: string | number | null | undefined,
+ type: "date" | "datetime",
+ ): string => {
+ return prettyDate(value, type, locale);
+ },
+ [locale],
+ );
+}
+
+/**
+ * Hook that provides locale-aware relative time formatting
+ */
+export function useTimeAgo() {
+ const { locale } = useLocale();
+
+ return useCallback(
+ (value: string | number | null | undefined): string => {
+ return timeAgo(value, locale);
+ },
+ [locale],
+ );
+}
+
+/**
+ * Hook that provides locale-aware timezone abbreviation
+ */
+export function useShortTimeZone() {
+ const { locale } = useLocale();
+
+ return useCallback(
+ (timezone: string): string => {
+ return getShortTimeZone(timezone, locale);
+ },
+ [locale],
+ );
+}
diff --git a/frontend/src/hooks/useTimer.ts b/frontend/src/hooks/useTimer.ts
index b2d42dd95a..3a31c4365d 100644
--- a/frontend/src/hooks/useTimer.ts
+++ b/frontend/src/hooks/useTimer.ts
@@ -1,6 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { useEffect, useRef, useState } from "react";
+import { useNumberFormatter } from "react-aria";
import useEvent from "react-use-event-hook";
/**
@@ -11,6 +12,12 @@ export function useTimer() {
const [time, setTime] = useState(0);
const interval = useRef<number>(undefined);
+ // one decimal place, exactly
+ const numberFormatter = useNumberFormatter({
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1,
+ });
+
const start = useEvent(() => {
interval.current = window.setInterval(() => {
setTime((time) => time + 0.1);
@@ -36,11 +43,7 @@ export function useTimer() {
}, []);
return {
- // one decimal place, exactly
- time: new Intl.NumberFormat("en-US", {
- minimumFractionDigits: 1,
- maximumFractionDigits: 1,
- }).format(time),
+ time: numberFormatter.format(time),
start,
stop,
clear,
diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsx
index ac45be7218..59fe1db2b9 100644
--- a/frontend/src/mount.tsx
+++ b/frontend/src/mount.tsx
@@ -26,7 +26,6 @@ import {
parseConfigOverrides,
parseUserConfig,
} from "./core/config/config-schema";
-import { LocaleProvider } from "./core/i18n/locale-provider";
import { MarimoApp, preloadPage } from "./core/MarimoApp";
import { type AppMode, initialModeAtom, viewStateAtom } from "./core/mode";
import { cleanupAuthQueryParams } from "./core/network/auth";
@@ -83,11 +82,9 @@ export function mount(options: unknown, el: Element): Error | undefined {
root.render(
<Provider store={store}>
- <LocaleProvider>
- <ThemeProvider>
- <MarimoApp />
- </ThemeProvider>
- </LocaleProvider>
+ <ThemeProvider>
+ <MarimoApp />
+ </ThemeProvider>
</Provider>,
);
} catch (error) {
diff --git a/frontend/src/plugins/impl/RangeSliderPlugin.tsx b/frontend/src/plugins/impl/RangeSliderPlugin.tsx
index 616625406e..39b2c0e5f2 100644
--- a/frontend/src/plugins/impl/RangeSliderPlugin.tsx
+++ b/frontend/src/plugins/impl/RangeSliderPlugin.tsx
@@ -2,6 +2,7 @@
import { isEqual } from "lodash-es";
import { type JSX, useEffect, useId, useState } from "react";
+import { useLocale } from "react-aria";
import { z } from "zod";
import { cn } from "@/utils/cn";
import { prettyScientificNumber } from "@/utils/numbers";
@@ -82,6 +83,7 @@ const RangeSliderComponent = ({
valueMap,
}: RangeSliderProps): JSX.Element => {
const id = useId();
+ const { locale } = useLocale();
// Hold internal value
const [internalValue, setInternalValue] = useState(value);
@@ -150,9 +152,9 @@ const RangeSliderComponent = ({
/>
{showValue && (
<div className="text-xs text-muted-foreground min-w-[16px]">
- {`${prettyScientificNumber(
- valueMap(internalValue[0]),
- )}, ${prettyScientificNumber(valueMap(internalValue[1]))}`}
+ {`${prettyScientificNumber(valueMap(internalValue[0]), {
+ locale,
+ })}, ${prettyScientificNumber(valueMap(internalValue[1]), { locale })}`}
</div>
)}
</div>
diff --git a/frontend/src/plugins/impl/SliderPlugin.tsx b/frontend/src/plugins/impl/SliderPlugin.tsx
index 54d8a87ee8..a00b4f9ae7 100644
--- a/frontend/src/plugins/impl/SliderPlugin.tsx
+++ b/frontend/src/plugins/impl/SliderPlugin.tsx
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { type JSX, useEffect, useId, useState } from "react";
+import { useLocale } from "react-aria";
import { z } from "zod";
import { NumberField } from "@/components/ui/number-field";
import { cn } from "@/utils/cn";
@@ -85,6 +86,7 @@ const SliderComponent = ({
disabled,
}: SliderProps): JSX.Element => {
const id = useId();
+ const { locale } = useLocale();
// Hold internal value
const [internalValue, setInternalValue] = useState(value);
@@ -138,7 +140,7 @@ const SliderComponent = ({
/>
{showValue && (
<div className="text-xs text-muted-foreground min-w-[16px]">
- {prettyScientificNumber(valueMap(internalValue))}
+ {prettyScientificNumber(valueMap(internalValue), { locale })}
</div>
)}
{includeInput && (
diff --git a/frontend/src/plugins/impl/data-explorer/components/column-summary.tsx b/frontend/src/plugins/impl/data-explorer/components/column-summary.tsx
index b428ccf527..8686bbe39d 100644
--- a/frontend/src/plugins/impl/data-explorer/components/column-summary.tsx
+++ b/frontend/src/plugins/impl/data-explorer/components/column-summary.tsx
@@ -3,6 +3,7 @@
import type { Schema } from "compassql/build/src/schema";
import { BarChartBigIcon } from "lucide-react";
import React, { useState } from "react";
+import { useDateFormatter, useNumberFormatter } from "react-aria";
import { Button } from "@/components/ui/button";
import {
Select,
@@ -131,7 +132,9 @@ export const ColumnSummary: React.FC<Props> = ({ schema }) => {
{STAT_KEYS.map((key) => (
<div key={key} className="flex flex-row gap-2 min-w-[100px]">
<span className="font-semibold">{key}</span>
- <span>{formatStat(stats?.[key])}</span>
+ <span>
+ <FormatStat value={stats?.[key]} />
+ </span>
</div>
))}
</div>
@@ -151,24 +154,28 @@ const STAT_KEYS = [
"stdev",
];
-function formatStat(value: unknown) {
+const FormatStat = ({ value }: { value: unknown }) => {
+ // Decimal .2
+ const numberFormatter = useNumberFormatter({
+ maximumFractionDigits: 2,
+ });
+
+ // Just day, month, year
+ const dateFormatter = useDateFormatter({
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ });
+
if (typeof value === "number") {
- // Decimal .2
- return new Intl.NumberFormat("en-US", {
- maximumFractionDigits: 2,
- }).format(value);
+ return numberFormatter.format(value);
}
if (typeof value === "string") {
return value;
}
if (typeof value === "object" && value instanceof Date) {
- // Just day, month, year
- return new Intl.DateTimeFormat("en-US", {
- year: "numeric",
- month: "short",
- day: "numeric",
- }).format(value);
+ return dateFormatter.format(value);
}
return String(value);
-}
+};
diff --git a/frontend/src/plugins/layout/StatPlugin.tsx b/frontend/src/plugins/layout/StatPlugin.tsx
index ce78b6171c..60f71c00b8 100644
--- a/frontend/src/plugins/layout/StatPlugin.tsx
+++ b/frontend/src/plugins/layout/StatPlugin.tsx
@@ -2,6 +2,7 @@
import { TriangleIcon } from "lucide-react";
import type { JSX } from "react";
+import { useLocale } from "react-aria";
import { z } from "zod";
import { cn } from "@/utils/cn";
import { prettyNumber } from "@/utils/numbers";
@@ -41,6 +42,8 @@ export const StatComponent: React.FC<Data> = ({
bordered,
direction,
}) => {
+ const { locale } = useLocale();
+
const renderPrettyValue = () => {
if (value == null) {
return <i>No value</i>;
@@ -51,7 +54,7 @@ export const StatComponent: React.FC<Data> = ({
}
if (typeof value === "number") {
- return prettyNumber(value);
+ return prettyNumber(value, locale);
}
if (typeof value === "boolean") {
diff --git a/frontend/src/utils/__tests__/dates.test.ts b/frontend/src/utils/__tests__/dates.test.ts
index d3c958bb50..0a976a58a5 100644
--- a/frontend/src/utils/__tests__/dates.test.ts
+++ b/frontend/src/utils/__tests__/dates.test.ts
@@ -8,6 +8,8 @@ import {
timeAgo,
} from "../dates";
+const locale = "en-US";
+
describe("dates", () => {
// Save original timezone
let originalTimezone: string | undefined;
@@ -25,36 +27,38 @@ describe("dates", () => {
describe("prettyDate", () => {
it("returns empty string for null or undefined", () => {
- expect(prettyDate(null, "date")).toBe("");
- expect(prettyDate(undefined, "date")).toBe("");
+ expect(prettyDate(null, "date", locale)).toBe("");
+ expect(prettyDate(undefined, "date", locale)).toBe("");
});
it("formats date correctly", () => {
const date = new Date("2023-05-15T12:00:00Z");
// Using a regex to match the pattern since exact format may vary by locale
- expect(prettyDate(date.toISOString(), "date")).toMatch(/May 15, 2023/);
+ expect(prettyDate(date.toISOString(), "date", locale)).toMatch(
+ /May 15, 2023/,
+ );
});
it("formats datetime correctly", () => {
const date = new Date("2023-05-15T12:00:00Z");
- expect(prettyDate(date.toISOString(), "datetime")).toMatch(
+ expect(prettyDate(date.toISOString(), "datetime", locale)).toMatch(
/May 15, 2023/,
);
});
it("handles errors gracefully", () => {
- expect(prettyDate("invalid-date", "date")).toBe("Invalid Date");
+ expect(prettyDate("invalid-date", "date", locale)).toBe("Invalid Date");
});
it("handles numeric timestamp input", () => {
const timestamp = 1_684_152_000_000; // 2023-05-15T12:00:00Z in milliseconds
- expect(prettyDate(timestamp, "date")).toMatch(/May 15, 2023/);
+ expect(prettyDate(timestamp, "date", locale)).toMatch(/May 15, 2023/);
});
it("preserves timezone for datetime type", () => {
// This date is in winter time to avoid daylight saving time issues
const date = new Date("2023-01-15T15:30:00Z");
- expect(prettyDate(date.toISOString(), "datetime")).toMatch(
+ expect(prettyDate(date.toISOString(), "datetime", locale)).toMatch(
/Jan 15, 2023/,
);
});
@@ -62,7 +66,9 @@ describe("dates", () => {
it("drops timezone for date type by using UTC", () => {
// Create a date that would be different days in different timezones
const date = new Date("2023-05-15T23:30:00Z"); // Late in the day UTC
- expect(prettyDate(date.toISOString(), "date")).toMatch(/May 15, 2023/);
+ expect(prettyDate(date.toISOString(), "date", locale)).toMatch(
+ /May 15, 2023/,
+ );
});
describe("with different locales", () => {
@@ -86,7 +92,9 @@ describe("dates", () => {
};
const date = new Date("2023-05-15T12:00:00Z");
- expect(prettyDate(date.toISOString(), "date")).toBe("15 mai 2023");
+ expect(prettyDate(date.toISOString(), "date", locale)).toBe(
+ "15 mai 2023",
+ );
});
});
});
@@ -94,34 +102,42 @@ describe("dates", () => {
describe("exactDateTime", () => {
it("formats date without milliseconds", () => {
const date = new Date("2023-05-15T12:00:00.000Z");
- expect(exactDateTime(date, undefined)).toBe("2023-05-15 12:00:00");
+ expect(exactDateTime(date, undefined, locale)).toBe(
+ "2023-05-15 12:00:00",
+ );
});
it("formats date with milliseconds", () => {
const date = new Date("2023-05-15T12:00:00.123Z");
- expect(exactDateTime(date, undefined)).toBe("2023-05-15 12:00:00.123");
+ expect(exactDateTime(date, undefined, locale)).toBe(
+ "2023-05-15 12:00:00.123",
+ );
});
it("formats date in UTC when renderInUTC is true", () => {
const date = new Date("2023-05-15T12:00:00.000Z");
- expect(exactDateTime(date, "UTC")).toBe("2023-05-15 12:00:00 UTC");
+ expect(exactDateTime(date, "UTC", locale)).toBe(
+ "2023-05-15 12:00:00 UTC",
+ );
});
it("formats date with milliseconds in UTC when renderInUTC is true", () => {
const date = new Date("2023-05-15T12:00:00.123Z");
- expect(exactDateTime(date, "UTC")).toBe("2023-05-15 12:00:00.123 UTC");
+ expect(exactDateTime(date, "UTC", locale)).toBe(
+ "2023-05-15 12:00:00.123 UTC",
+ );
});
it("formats date in America/New_York timezone", () => {
const date = new Date("2023-05-15T12:00:00.000Z");
- expect(exactDateTime(date, "America/New_York")).toBe(
+ expect(exactDateTime(date, "America/New_York", locale)).toBe(
"2023-05-15 08:00:00 EDT",
);
});
it("formats date with milliseconds in America/New_York timezone", () => {
const date = new Date("2023-05-15T12:00:00.123Z");
- expect(exactDateTime(date, "America/New_York")).toBe(
+ expect(exactDateTime(date, "America/New_York", locale)).toBe(
"2023-05-15 08:00:00.123 EDT",
);
});
@@ -129,42 +145,47 @@ describe("dates", () => {
describe("timeAgo", () => {
it("returns empty string for null, undefined, or 0", () => {
- expect(timeAgo(null)).toBe("");
- expect(timeAgo(undefined)).toBe("");
- expect(timeAgo(0)).toBe("");
+ expect(timeAgo(null, locale)).toBe("");
+ expect(timeAgo(undefined, locale)).toBe("");
+ expect(timeAgo(0, locale)).toBe("");
});
it("formats today's date correctly", () => {
const today = new Date();
- const result = timeAgo(today.toISOString());
+ const result = timeAgo(today.toISOString(), locale);
expect(result).toMatch(/Today at/);
});
it("formats yesterday's date correctly", () => {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
- const result = timeAgo(yesterday.toISOString());
+ const result = timeAgo(yesterday.toISOString(), locale);
expect(result).toMatch(/Yesterday at/);
});
it("formats older dates correctly", () => {
const oldDate = new Date("2020-01-01T12:00:00Z");
- const result = timeAgo(oldDate.toISOString());
+ const result = timeAgo(oldDate.toISOString(), locale);
expect(result).toMatch(/Jan 1, 2020 at/);
});
it("handles errors gracefully", () => {
- expect(timeAgo("invalid-date")).toBe("Invalid Date at Invalid Date");
+ expect(timeAgo("invalid-date", locale)).toBe(
+ "Invalid Date at Invalid Date",
+ );
});
});
describe("getShortTimeZone", () => {
it("returns the short timezone", () => {
- expect(getShortTimeZone("America/New_York")).toBeOneOf(["EDT", "EST"]);
+ expect(getShortTimeZone("America/New_York", locale)).toBeOneOf([
+ "EDT",
+ "EST",
+ ]);
});
it("handles errors gracefully", () => {
- expect(getShortTimeZone("MarimoLand")).toBe("MarimoLand");
+ expect(getShortTimeZone("MarimoLand", locale)).toBe("MarimoLand");
});
});
diff --git a/frontend/src/utils/__tests__/numbers.test.ts b/frontend/src/utils/__tests__/numbers.test.ts
index 5af8268d50..80698b2fdc 100644
--- a/frontend/src/utils/__tests__/numbers.test.ts
+++ b/frontend/src/utils/__tests__/numbers.test.ts
@@ -6,24 +6,32 @@ import {
prettyScientificNumber,
} from "../numbers";
+const locale = "en-US";
+
describe("prettyNumber", () => {
it("should format numbers", () => {
- expect(prettyNumber(123_456_789)).toBe("123,456,789");
- expect(prettyNumber(1234.567_89)).toBe("1,234.57");
- expect(prettyNumber(0)).toBe("0");
+ expect(prettyNumber(123_456_789, locale)).toBe("123,456,789");
+ expect(prettyNumber(1234.567_89, locale)).toBe("1,234.57");
+ expect(prettyNumber(0, locale)).toBe("0");
});
});
+const options = { locale };
+
describe("prettyScientificNumber", () => {
it("should handle special cases", () => {
- expect(prettyScientificNumber(0)).toBe("0");
- expect(prettyScientificNumber(Number.NaN)).toBe("NaN");
- expect(prettyScientificNumber(Number.POSITIVE_INFINITY)).toBe("Infinity");
- expect(prettyScientificNumber(Number.NEGATIVE_INFINITY)).toBe("-Infinity");
+ expect(prettyScientificNumber(0, options)).toBe("0");
+ expect(prettyScientificNumber(Number.NaN, options)).toBe("NaN");
+ expect(prettyScientificNumber(Number.POSITIVE_INFINITY, options)).toBe(
+ "Infinity",
+ );
+ expect(prettyScientificNumber(Number.NEGATIVE_INFINITY, options)).toBe(
+ "-Infinity",
+ );
});
it("should format decimals with scientific notation, ignoring integer part rounding", () => {
- const opts = { shouldRound: true };
+ const opts = { shouldRound: true, locale };
expect(prettyScientificNumber(123_456, opts)).toBe("123,456");
expect(prettyScientificNumber(123_456.7, opts)).toBe("123,456.7");
expect(prettyScientificNumber(12_345.6789, opts)).toBe("12,345.68");
@@ -40,10 +48,10 @@ describe("prettyScientificNumber", () => {
});
it("should not round numbers when shouldRound is false", () => {
- expect(prettyScientificNumber(123_456)).toBe("123,456");
- expect(prettyScientificNumber(123_456.7)).toBe("123,456.7");
- expect(prettyScientificNumber(12_345.6789)).toBe("12,345.6789");
- expect(prettyScientificNumber(1.234_567_891_011_12)).toBe(
+ expect(prettyScientificNumber(123_456, options)).toBe("123,456");
+ expect(prettyScientificNumber(123_456.7, options)).toBe("123,456.7");
+ expect(prettyScientificNumber(12_345.6789, options)).toBe("12,345.6789");
+ expect(prettyScientificNumber(1.234_567_891_011_12, options)).toBe(
"1.23456789101112",
);
});
@@ -51,26 +59,30 @@ describe("prettyScientificNumber", () => {
describe("prettyEngineeringNumber", () => {
it("should handle special cases", () => {
- expect(prettyEngineeringNumber(0)).toBe("0");
- expect(prettyEngineeringNumber(-0)).toBe("0"); // Test with negative zero
- expect(prettyEngineeringNumber(Number.NaN)).toBe("NaN");
- expect(prettyEngineeringNumber(Number.POSITIVE_INFINITY)).toBe("Infinity");
- expect(prettyEngineeringNumber(Number.NEGATIVE_INFINITY)).toBe("-Infinity");
+ expect(prettyEngineeringNumber(0, locale)).toBe("0");
+ expect(prettyEngineeringNumber(-0, locale)).toBe("0"); // Test with negative zero
+ expect(prettyEngineeringNumber(Number.NaN, locale)).toBe("NaN");
+ expect(prettyEngineeringNumber(Number.POSITIVE_INFINITY, locale)).toBe(
+ "Infinity",
+ );
+ expect(prettyEngineeringNumber(Number.NEGATIVE_INFINITY, locale)).toBe(
+ "-Infinity",
+ );
});
it("should format decimals with engineering notation, ignoring integer part", () => {
- expect(prettyEngineeringNumber(123_456)).toBe("123k");
- expect(prettyEngineeringNumber(123_456.7)).toBe("123k");
- expect(prettyEngineeringNumber(12_345.6789)).toBe("12.3k");
- expect(prettyEngineeringNumber(1.2345)).toBe("1.23");
- expect(prettyEngineeringNumber(1.000_001_234)).toBe("1");
- expect(prettyEngineeringNumber(0.12)).toBe("120m");
- expect(prettyEngineeringNumber(0.1234)).toBe("123m");
- expect(prettyEngineeringNumber(0.000_123_4)).toBe("123µ");
- expect(prettyEngineeringNumber(-1.2345)).toBe("-1.23"); // Test with negative numbers
- expect(prettyEngineeringNumber(-1.000_001_234)).toBe("-1");
- expect(prettyEngineeringNumber(-0.12)).toBe("-120m");
- expect(prettyEngineeringNumber(-0.1234)).toBe("-123m");
- expect(prettyEngineeringNumber(-0.000_123_4)).toBe("-123µ");
+ expect(prettyEngineeringNumber(123_456, locale)).toBe("123k");
+ expect(prettyEngineeringNumber(123_456.7, locale)).toBe("123k");
+ expect(prettyEngineeringNumber(12_345.6789, locale)).toBe("12.3k");
+ expect(prettyEngineeringNumber(1.2345, locale)).toBe("1.23");
+ expect(prettyEngineeringNumber(1.000_001_234, locale)).toBe("1");
+ expect(prettyEngineeringNumber(0.12, locale)).toBe("120m");
+ expect(prettyEngineeringNumber(0.1234, locale)).toBe("123m");
+ expect(prettyEngineeringNumber(0.000_123_4, locale)).toBe("123µ");
+ expect(prettyEngineeringNumber(-1.2345, locale)).toBe("-1.23"); // Test with negative numbers
+ expect(prettyEngineeringNumber(-1.000_001_234, locale)).toBe("-1");
+ expect(prettyEngineeringNumber(-0.12, locale)).toBe("-120m");
+ expect(prettyEngineeringNumber(-0.1234, locale)).toBe("-123m");
+ expect(prettyEngineeringNumber(-0.000_123_4, locale)).toBe("-123µ");
});
});
diff --git a/frontend/src/utils/__tests__/once.test.ts b/frontend/src/utils/__tests__/once.test.ts
new file mode 100644
index 0000000000..43e8fc2443
--- /dev/null
+++ b/frontend/src/utils/__tests__/once.test.ts
@@ -0,0 +1,187 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it, vi } from "vitest";
+import { memoizeLastValue, once } from "../once";
+
+describe("once", () => {
+ it("should call function only once", () => {
+ const fn = vi.fn(() => "result");
+ const onceFn = once(fn);
+
+ const result1 = onceFn();
+ const result2 = onceFn();
+
+ expect(result1).toBe("result");
+ expect(result2).toBe("result");
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("should return the same result on subsequent calls", () => {
+ let counter = 0;
+ const fn = () => ++counter;
+ const onceFn = once(fn);
+
+ expect(onceFn()).toBe(1);
+ expect(onceFn()).toBe(1);
+ expect(onceFn()).toBe(1);
+ });
+});
+
+describe("memoizeLastValue", () => {
+ it("should memoize result for same arguments", () => {
+ const fn = vi.fn((a: number, b: string) => `${a}-${b}`);
+ const memoizedFn = memoizeLastValue(fn);
+
+ const result1 = memoizedFn(1, "test");
+ const result2 = memoizedFn(1, "test");
+
+ expect(result1).toBe("1-test");
+ expect(result2).toBe("1-test");
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("should recompute for different arguments", () => {
+ const fn = vi.fn((a: number) => a * 2);
+ const memoizedFn = memoizeLastValue(fn);
+
+ const result1 = memoizedFn(5);
+ const result2 = memoizedFn(10);
+ const result3 = memoizedFn(5); // Should recompute since args changed from previous call
+
+ expect(result1).toBe(10);
+ expect(result2).toBe(20);
+ expect(result3).toBe(10);
+ expect(fn).toHaveBeenCalledTimes(3);
+ });
+
+ it("should handle no arguments", () => {
+ const fn = vi.fn(() => "no-args");
+ const memoizedFn = memoizeLastValue(fn);
+
+ const result1 = memoizedFn();
+ const result2 = memoizedFn();
+
+ expect(result1).toBe("no-args");
+ expect(result2).toBe("no-args");
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("should handle single argument", () => {
+ const fn = vi.fn((x: number) => x + 1);
+ const memoizedFn = memoizeLastValue(fn);
+
+ expect(memoizedFn(5)).toBe(6);
+ expect(memoizedFn(5)).toBe(6);
+ expect(memoizedFn(3)).toBe(4);
+
+ expect(fn).toHaveBeenCalledTimes(2);
+ });
+
+ it("should handle multiple arguments", () => {
+ const fn = vi.fn((a: number, b: string, c: boolean) => ({ a, b, c }));
+ const memoizedFn = memoizeLastValue(fn);
+
+ const result1 = memoizedFn(1, "hello", true);
+ const result2 = memoizedFn(1, "hello", true);
+ const result3 = memoizedFn(1, "hello", false);
+
+ expect(result1).toEqual({ a: 1, b: "hello", c: true });
+ expect(result2).toEqual({ a: 1, b: "hello", c: true });
+ expect(result3).toEqual({ a: 1, b: "hello", c: false });
+ expect(fn).toHaveBeenCalledTimes(2);
+ });
+
+ it("should use shallow comparison for objects", () => {
+ const fn = vi.fn((obj: { x: number }) => obj.x * 2);
+ const memoizedFn = memoizeLastValue(fn);
+
+ const obj1 = { x: 5 };
+ const obj2 = { x: 5 }; // Different reference but same content
+
+ const result1 = memoizedFn(obj1);
+ const result2 = memoizedFn(obj1); // Same reference
+ const result3 = memoizedFn(obj2); // Different reference
+
+ expect(result1).toBe(10);
+ expect(result2).toBe(10);
+ expect(result3).toBe(10);
+ expect(fn).toHaveBeenCalledTimes(2); // obj1 (twice with same ref) and obj2 (different ref)
+ });
+
+ it("should handle arrays", () => {
+ const fn = vi.fn((arr: number[]) => arr.reduce((sum, x) => sum + x, 0));
+ const memoizedFn = memoizeLastValue(fn);
+
+ const result1 = memoizedFn([1, 2, 3]);
+ const result2 = memoizedFn([1, 2, 3]); // Different array reference but same content
+ const result3 = memoizedFn([1, 2, 4]); // Different content
+
+ expect(result1).toBe(6);
+ expect(result2).toBe(6);
+ expect(result3).toBe(7);
+ expect(fn).toHaveBeenCalledTimes(3); // Each call has different array reference
+ });
+
+ it("should handle mixed argument types", () => {
+ const fn = vi.fn(
+ (num: number, str: string, arr: number[], obj: { key: string }) =>
+ `${num}-${str}-${arr.length}-${obj.key}`,
+ );
+ const memoizedFn = memoizeLastValue(fn);
+
+ const arr = [1, 2, 3];
+ const obj = { key: "test" };
+
+ const result1 = memoizedFn(42, "hello", arr, obj);
+ const result2 = memoizedFn(42, "hello", arr, obj); // Same references
+ const result3 = memoizedFn(42, "hello", [1, 2, 3], { key: "test" }); // Different references
+
+ expect(result1).toBe("42-hello-3-test");
+ expect(result2).toBe("42-hello-3-test");
+ expect(result3).toBe("42-hello-3-test");
+ expect(fn).toHaveBeenCalledTimes(2);
+ });
+
+ it("should handle undefined and null arguments", () => {
+ const fn = vi.fn((a?: string, b?: null) => `${a}-${b}`);
+ const memoizedFn = memoizeLastValue(fn);
+
+ const result1 = memoizedFn(undefined, null);
+ const result2 = memoizedFn(undefined, null);
+ const result3 = memoizedFn("test", null);
+
+ expect(result1).toBe("undefined-null");
+ expect(result2).toBe("undefined-null");
+ expect(result3).toBe("test-null");
+ expect(fn).toHaveBeenCalledTimes(2);
+ });
+
+ it("should preserve function context", () => {
+ const context = {
+ value: 10,
+ fn: vi.fn(function (this: { value: number }, multiplier: number) {
+ return this.value * multiplier;
+ }),
+ };
+
+ const memoizedFn = memoizeLastValue(context.fn);
+
+ const result1 = memoizedFn.call(context, 2);
+ const result2 = memoizedFn.call(context, 2);
+
+ expect(result1).toBe(20);
+ expect(result2).toBe(20);
+ expect(context.fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("should handle functions that throw errors", () => {
+ const error = new Error("test error");
+ const fn = vi.fn(() => {
+ throw error;
+ });
+ const memoizedFn = memoizeLastValue(fn);
+
+ expect(() => memoizedFn()).toThrow("test error");
+ expect(() => memoizedFn()).toThrow("test error"); // Should throw cached error
+ expect(fn).toHaveBeenCalledTimes(1); // Error should be memoized too
+ });
+});
diff --git a/frontend/src/utils/dates.ts b/frontend/src/utils/dates.ts
index cef221cf70..43cacebe26 100644
--- a/frontend/src/utils/dates.ts
+++ b/frontend/src/utils/dates.ts
@@ -7,6 +7,7 @@ import { Logger } from "./Logger";
export function prettyDate(
value: string | number | null | undefined,
type: "date" | "datetime",
+ locale: string,
): string {
if (value == null) {
return "";
@@ -16,7 +17,7 @@ export function prettyDate(
// If type is date, drop the timezone by rendering in UTC
// since dates are absolute
if (type === "date") {
- return new Date(value).toLocaleDateString(undefined, {
+ return new Date(value).toLocaleDateString(locale, {
year: "numeric",
month: "short",
day: "numeric",
@@ -25,7 +26,7 @@ export function prettyDate(
}
// For datetime, we keep the original timezone
- return new Date(value).toLocaleDateString(undefined, {
+ return new Date(value).toLocaleDateString(locale, {
year: "numeric",
month: "short",
day: "numeric",
@@ -43,12 +44,13 @@ export function prettyDate(
export function exactDateTime(
value: Date,
timezone: string | undefined,
+ locale: string,
): string {
const hasSubSeconds = value.getUTCMilliseconds() !== 0;
try {
if (timezone) {
const valueWithTimezone = new TZDate(value, timezone);
- const shortTimeZone = getShortTimeZone(timezone);
+ const shortTimeZone = getShortTimeZone(timezone, locale);
if (hasSubSeconds) {
return `${formatDate(valueWithTimezone, "yyyy-MM-dd HH:mm:ss.SSS")} ${shortTimeZone}`;
}
@@ -66,9 +68,9 @@ export function exactDateTime(
}
}
-export function getShortTimeZone(timezone: string): string {
+export function getShortTimeZone(timezone: string, locale: string): string {
try {
- const abbrev = new Intl.DateTimeFormat("en-US", {
+ const abbrev = new Intl.DateTimeFormat(locale, {
timeZone: timezone,
timeZoneName: "short",
})
@@ -88,7 +90,10 @@ export function getShortTimeZone(timezone: string): string {
*
* If a date in the past, it should say "<date> at 8:00 AM".
*/
-export function timeAgo(value: string | number | null | undefined): string {
+export function timeAgo(
+ value: string | number | null | undefined,
+ locale: string,
+): string {
if (value == null) {
return "";
}
@@ -103,22 +108,22 @@ export function timeAgo(value: string | number | null | undefined): string {
yesterday.setDate(yesterday.getDate() - 1);
if (date.toDateString() === today.toDateString()) {
- return `Today at ${date.toLocaleTimeString(undefined, {
+ return `Today at ${date.toLocaleTimeString(locale, {
hour: "numeric",
minute: "numeric",
})}`;
}
if (date.toDateString() === yesterday.toDateString()) {
- return `Yesterday at ${date.toLocaleTimeString(undefined, {
+ return `Yesterday at ${date.toLocaleTimeString(locale, {
hour: "numeric",
minute: "numeric",
})}`;
}
- return `${date.toLocaleDateString(undefined, {
+ return `${date.toLocaleDateString(locale, {
year: "numeric",
month: "short",
day: "numeric",
- })} at ${date.toLocaleTimeString(undefined, {
+ })} at ${date.toLocaleTimeString(locale, {
hour: "numeric",
minute: "numeric",
})}`;
diff --git a/frontend/src/utils/numbers.ts b/frontend/src/utils/numbers.ts
index 3e57ea3881..1c2b3986e0 100644
--- a/frontend/src/utils/numbers.ts
+++ b/frontend/src/utils/numbers.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
-export function prettyNumber(value: unknown): string {
+export function prettyNumber(value: unknown, locale: string): string {
if (value === undefined || value === null) {
return "";
}
@@ -18,7 +18,7 @@ export function prettyNumber(value: unknown): string {
}
if (typeof value === "number" || typeof value === "bigint") {
- return value.toLocaleString(undefined, {
+ return value.toLocaleString(locale, {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
});
@@ -45,9 +45,9 @@ function scientificSpecialCase(value: number): string | null {
export function prettyScientificNumber(
value: number,
opts: {
- // Default to false
- shouldRound?: boolean;
- } = {},
+ shouldRound?: boolean; // Default to false
+ locale: string;
+ },
): string {
// Handle special cases first
const specialCase = scientificSpecialCase(value);
@@ -58,7 +58,7 @@ export function prettyScientificNumber(
// Determine if the number should be in scientific notation
const absValue = Math.abs(value);
if (absValue < 1e-2 || absValue >= 1e6) {
- return new Intl.NumberFormat(undefined, {
+ return new Intl.NumberFormat(opts.locale, {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
notation: "scientific",
@@ -67,18 +67,18 @@ export function prettyScientificNumber(
.toLowerCase();
}
- const { shouldRound } = opts;
+ const { shouldRound, locale } = opts;
if (shouldRound) {
// Number has an integer part, format with 2 decimal places
- return new Intl.NumberFormat(undefined, {
+ return new Intl.NumberFormat(locale, {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
}).format(value);
}
// Don't round
- return value.toLocaleString(undefined, {
+ return value.toLocaleString(locale, {
minimumFractionDigits: 0,
maximumFractionDigits: 100,
});
@@ -104,14 +104,14 @@ const prefixes = {
"-24": "y",
};
-export function prettyEngineeringNumber(value: number): string {
+export function prettyEngineeringNumber(value: number, locale: string): string {
// Handle special cases first
const specialCase = scientificSpecialCase(value);
if (specialCase !== null) {
return specialCase;
}
- const [mant, exp] = new Intl.NumberFormat("en-us", {
+ const [mant, exp] = new Intl.NumberFormat(locale, {
notation: "engineering",
maximumSignificantDigits: 3,
})
diff --git a/frontend/src/utils/once.ts b/frontend/src/utils/once.ts
index 8e96ea782c..5c277f2dbf 100644
--- a/frontend/src/utils/once.ts
+++ b/frontend/src/utils/once.ts
@@ -1,5 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { arrayShallowEquals } from "./arrays";
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function once<T extends (...args: any[]) => any>(fn: T): T {
let result: ReturnType<T>;
@@ -15,3 +17,33 @@ export function once<T extends (...args: any[]) => any>(fn: T): T {
return result;
} as T;
}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export function memoizeLastValue<T extends (...args: any[]) => any>(fn: T): T {
+ let result: ReturnType<T>;
+ let lastArgs: Parameters<T> | undefined;
+ let lastError: unknown;
+ let hasError = false;
+
+ return function (
+ this: ThisParameterType<T>,
+ ...args: Parameters<T>
+ ): ReturnType<T> {
+ if (lastArgs === undefined || !arrayShallowEquals(args, lastArgs)) {
+ try {
+ result = fn.apply(this, args) as ReturnType<T>;
+ hasError = false;
+ lastError = undefined;
+ } catch (error) {
+ hasError = true;
+ lastError = error;
+ }
+ lastArgs = args;
+ }
+
+ if (hasError) {
+ throw lastError;
+ }
+ return result;
+ } as T;
+}