{periods.map((x) => (
-
- {truncate(formatX(x), PERIOD_MAX)}
+
+ {truncate(formatX(x, locale), PERIOD_MAX)}
))}
@@ -160,7 +170,9 @@ function Column({
unit,
label,
end,
+ locale,
}: {
+ locale?: string;
point: ColumnPoint;
index: number;
top: number;
@@ -170,8 +182,8 @@ function Column({
label?: string;
end: boolean;
}) {
- const value = formatNumber(point.y as number);
- const period = formatX(point.x);
+ const value = formatNumber(point.y as number, locale);
+ const period = formatX(point.x, locale);
const text = `${value}${unit}, ${period}${label ? ` — ${label}` : ""}${point.note ? `. ${point.note}` : ""}`;
const className = `ck-col${negative ? " ck-col-neg" : ""}${end ? " ck-pt-end" : ""}`;
const style = { top: `${top}%`, height: `${Math.max(size, 0.5)}%` };
diff --git a/src/react/LineChart.tsx b/src/react/LineChart.tsx
index 574f9f3..8727dfb 100644
--- a/src/react/LineChart.tsx
+++ b/src/react/LineChart.tsx
@@ -43,6 +43,11 @@ export interface LineChartProps {
markers?: LineMarkers;
/** A light fill under each line, in the series' own token colour. */
area?: boolean;
+ /** Explicit BCP 47 locale; omitted preserves the existing English output. */
+ locale?: string;
+ /** Translate visible/accessibility words with the product's own dictionary. */
+ periodLabel?: string;
+ preliminaryLabel?: string;
}
/** Points with more than this many on one series draw smaller dots. */
@@ -64,6 +69,9 @@ export function LineChart({
height = 208,
markers = "all",
area = false,
+ locale,
+ periodLabel = "Period",
+ preliminaryLabel = "preliminary",
}: LineChartProps) {
const scale = valueScale(
series.flatMap((s) => s.points.map((p) => p.y)),
@@ -72,9 +80,12 @@ export function LineChart({
const extent = xExtent(series);
const dated = series.some((s) => s.points.some((p) => isDate(p.x)));
const xTicks: Tick[] = dated
- ? timeTicks(extent[0], extent[1])
- : numberTicks(extent[0], extent[1]);
- const yTicks = scale.ticks.map((v) => ({ pos: yPercent(v, scale), label: formatNumber(v) }));
+ ? timeTicks(extent[0], extent[1], 5, locale)
+ : numberTicks(extent[0], extent[1], 5, locale);
+ const yTicks = scale.ticks.map((v) => ({
+ pos: yPercent(v, scale),
+ label: formatNumber(v, locale),
+ }));
const gutter = Math.max(...yTicks.map((t) => t.label.length)) + 1;
const placed = series.map((s) =>
s.points.map((p) => ({ point: p, x: xPercent(p.x, extent), y: yPercent(p.y, scale) })),
@@ -85,12 +96,14 @@ export function LineChart({
(a, b) => xPosition(a) - xPosition(b),
);
const table = {
- head: ["Period", ...series.map((s) => (unit ? `${s.label} (${unit})` : s.label))],
+ head: [periodLabel, ...series.map((s) => (unit ? `${s.label} (${unit})` : s.label))],
rows: xs.map((x) => [
- formatX(x),
+ formatX(x, locale),
...series.map((s) => {
const p = s.points.find((q) => q.x === x);
- return p ? `${formatNumber(p.y)}${p.preliminary ? " (preliminary)" : ""}` : "";
+ return p
+ ? `${formatNumber(p.y, locale)}${p.preliminary ? ` (${preliminaryLabel})` : ""}`
+ : "";
}),
]),
};
@@ -149,6 +162,8 @@ export function LineChart({
66 ? " ck-pt-end" : column && x < 33 ? " ck-pt-start" : "";
const className = column
? `ck-pt ck-pt-col${marked ? " ck-pt-marked" : ""}${edge}`
@@ -228,7 +247,7 @@ function Point({
const tip = (
- {formatNumber(point.y)}
+ {formatNumber(point.y, locale)}
{unit}
diff --git a/src/react/Timeline.tsx b/src/react/Timeline.tsx
index 5113aa5..ade1719 100644
--- a/src/react/Timeline.tsx
+++ b/src/react/Timeline.tsx
@@ -18,6 +18,8 @@ export interface TimelineProps {
/** ISO dates. Left out, the axis runs from the month of the first event to the month after the last. */
from?: string;
to?: string;
+ locale?: string;
+ tableLabels?: { date: string; event: string; effect: string };
}
/**
@@ -36,7 +38,7 @@ const LABEL = 30;
* right in the left part of the axis and to the left near its end, and is
* never wider than the room to its neighbour.
*/
-export function Timeline({ events, caption, from, to }: TimelineProps) {
+export function Timeline({ events, caption, from, to, locale, tableLabels }: TimelineProps) {
const sorted = [...events].sort((a, b) => xPosition(a.date) - xPosition(b.date));
const times = sorted.map((e) => xPosition(e.date));
const first = times[0] ?? Date.now();
@@ -51,11 +53,15 @@ export function Timeline({ events, caption, from, to }: TimelineProps) {
);
const lane = lanes(spans, 1);
const laneCount = Math.max(1, ...lane.map((l) => l + 1));
- const ticks = monthTicks(x0, x1);
+ const ticks = monthTicks(x0, x1, 6, locale);
let labelled = 0;
const table = {
- head: ["Date", "Event", "Effect"],
- rows: sorted.map((e) => [formatX(e.date), e.label, e.tone ?? ""]),
+ head: [
+ tableLabels?.date ?? "Date",
+ tableLabels?.event ?? "Event",
+ tableLabels?.effect ?? "Effect",
+ ],
+ rows: sorted.map((e) => [formatX(e.date, locale), e.label, e.tone ?? ""]),
};
return (
@@ -72,7 +78,7 @@ export function Timeline({ events, caption, from, to }: TimelineProps) {
const room = right
? Math.min(100, ...mates.filter(([a]) => a >= pos).map(([a]) => a)) - pos
: pos - Math.max(0, ...mates.filter(([, b]) => b <= pos).map(([, b]) => b));
- const text = `${formatX(e.date)}: ${e.label}`;
+ const text = `${formatX(e.date, locale)}: ${e.label}`;
return (
errors.push(e.message));
- await page.goto(base);
- if (dark) await page.evaluate(() => document.documentElement.classList.add("dark"));
- await page.waitForSelector(".ck-chart-line .ck-pt");
- await page.waitForTimeout(100);
- const defects = await page.evaluate(`(${CHART_DEFECTS_SOURCE})(document.body)`);
- const m = await page.evaluate(() => {
- const px = (el) => parseFloat(getComputedStyle(el).fontSize);
- const texts = [...document.querySelectorAll(".ck-chart *")].filter(
- (el) =>
- !el.closest(".ck-sr") &&
- [...el.childNodes].some((n) => n.nodeType === Node.TEXT_NODE && n.nodeValue.trim()) &&
- el.getBoundingClientRect().width > 0,
- );
- const path = document.querySelector(".ck-line-path");
- const ink = getComputedStyle(document.body).color;
- return {
- overflow: document.documentElement.scrollWidth - window.innerWidth,
- charts: document.querySelectorAll(".ck-chart").length,
- tables: document.querySelectorAll(".ck-chart .ck-chart-table").length,
- smallest: Math.min(...texts.map(px)),
- stroke: getComputedStyle(path).strokeWidth,
- lanes: document.querySelectorAll(".ck-tl-lane").length,
- points: document.querySelectorAll(".ck-pt:not(.ck-pt-col)").length,
- quiet: document.querySelectorAll(".ck-pt-col").length,
- quietShown: [...document.querySelectorAll(".ck-pt-col")].filter(
- (el) => getComputedStyle(el, "::before").opacity !== "0",
- ).length,
- quietMinHeight: Math.min(
- ...[...document.querySelectorAll(".ck-pt-col")].map(
- (el) => el.getBoundingClientRect().height,
+ for (const locale of [undefined, "de-CH"]) {
+ for (const width of [320, 390, 1280, 1440]) {
+ for (const dark of [false, true]) {
+ const name = `${width}px ${dark ? "dark" : "light"} ${locale ?? "default"}`;
+ const page = await browser.newPage({ viewport: { width, height: 900 } });
+ const errors = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.goto(locale ? `${base}?locale=${locale}` : base);
+ if (locale) {
+ check(
+ (await page
+ .locator(".ck-chart-line .ck-chart-table thead th")
+ .first()
+ .textContent()) === "Zeitraum",
+ `${name}: accessible period heading uses the app dictionary`,
+ );
+ check(
+ (
+ await page.locator(".ck-chart-line .ck-chart-table tbody").first().textContent()
+ ).includes("März"),
+ `${name}: dates use German month names`,
+ );
+ }
+ if (dark) await page.evaluate(() => document.documentElement.classList.add("dark"));
+ await page.waitForSelector(".ck-chart-line .ck-pt");
+ await page.waitForTimeout(100);
+ const defects = await page.evaluate(`(${CHART_DEFECTS_SOURCE})(document.body)`);
+ const m = await page.evaluate(() => {
+ const px = (el) => parseFloat(getComputedStyle(el).fontSize);
+ const texts = [...document.querySelectorAll(".ck-chart *")].filter(
+ (el) =>
+ !el.closest(".ck-sr") &&
+ [...el.childNodes].some((n) => n.nodeType === Node.TEXT_NODE && n.nodeValue.trim()) &&
+ el.getBoundingClientRect().width > 0,
+ );
+ const path = document.querySelector(".ck-line-path");
+ const ink = getComputedStyle(document.body).color;
+ return {
+ overflow: document.documentElement.scrollWidth - window.innerWidth,
+ charts: document.querySelectorAll(".ck-chart").length,
+ tables: document.querySelectorAll(".ck-chart .ck-chart-table").length,
+ smallest: Math.min(...texts.map(px)),
+ stroke: getComputedStyle(path).strokeWidth,
+ lanes: document.querySelectorAll(".ck-tl-lane").length,
+ points: document.querySelectorAll(".ck-pt:not(.ck-pt-col)").length,
+ quiet: document.querySelectorAll(".ck-pt-col").length,
+ quietShown: [...document.querySelectorAll(".ck-pt-col")].filter(
+ (el) => getComputedStyle(el, "::before").opacity !== "0",
+ ).length,
+ quietMinHeight: Math.min(
+ ...[...document.querySelectorAll(".ck-pt-col")].map(
+ (el) => el.getBoundingClientRect().height,
+ ),
),
- ),
- quietGap: (() => {
- const r = [...document.querySelectorAll(".ck-pt-col")].map((el) =>
- el.getBoundingClientRect(),
- );
- let gap = 0;
- for (let i = 1; i < r.length; i++) gap = Math.max(gap, r[i].left - r[i - 1].right);
- return gap;
- })(),
- area: document.querySelectorAll(".ck-line-area").length,
- areaFill: (() => {
- const a = document.querySelector(".ck-line-area");
- return a ? getComputedStyle(a).fill : "";
- })(),
- tickInk: getComputedStyle(document.querySelector(".ck-line-tick")).color,
- ink,
- tileCols: getComputedStyle(document.querySelector(".ck-tiles")).gridTemplateColumns.split(
- " ",
- ).length,
- };
- });
- check(
- defects.length === 0,
- `${name}: no chart text leaves its figure or overlaps another (${defects.slice(0, 6).join(" | ")})`,
- );
- check(m.overflow <= 0, `${name}: no horizontal scroll (${m.overflow}px over)`);
- check(m.smallest >= 12, `${name}: no label under 12px (${m.smallest}px)`);
- check(m.stroke === "2px", `${name}: the line is 2px whatever the plot's size (${m.stroke})`);
- check(
- m.charts >= 8 && m.tables >= 6,
- `${name}: ${m.charts} charts, ${m.tables} tables behind them`,
- );
- check(m.lanes >= 2, `${name}: colliding events took a second lane (${m.lanes} lanes)`);
- check(m.points === 18, `${name}: every value is a point (${m.points})`);
- check(
- m.quiet > 200 && m.quietShown === 0,
- `${name}: a year of closes draws no dots (${m.quietShown} of ${m.quiet} shown)`,
- );
- check(
- m.quietMinHeight >= 44 && m.quietGap <= 0.5,
- `${name}: hidden values are full-height strips that tile the plot (${m.quietMinHeight}px tall, gap ${m.quietGap}px)`,
- );
- check(
- m.area === 1 && m.areaFill && m.areaFill !== "none" && m.areaFill !== "rgb(0, 0, 0)",
- `${name}: area draws one light fill (${m.areaFill})`,
- );
- check(m.tileCols === (width < 640 ? 2 : 4), `${name}: tiles ${m.tileCols} across`);
- check(m.tickInk !== m.ink, `${name}: tick labels in the muted ink, not the text ink`);
- check(errors.length === 0, `${name}: no page errors ${errors.join(" | ")}`);
- if (process.env.CHARTKIT_SHOTS) {
- await page.screenshot({
- path: `${process.env.CHARTKIT_SHOTS}/demo-${width}-${dark ? "dark" : "light"}.png`,
- fullPage: true,
+ quietGap: (() => {
+ const r = [...document.querySelectorAll(".ck-pt-col")].map((el) =>
+ el.getBoundingClientRect(),
+ );
+ let gap = 0;
+ for (let i = 1; i < r.length; i++) gap = Math.max(gap, r[i].left - r[i - 1].right);
+ return gap;
+ })(),
+ area: document.querySelectorAll(".ck-line-area").length,
+ areaFill: (() => {
+ const a = document.querySelector(".ck-line-area");
+ return a ? getComputedStyle(a).fill : "";
+ })(),
+ tickInk: getComputedStyle(document.querySelector(".ck-line-tick")).color,
+ ink,
+ tileCols: getComputedStyle(
+ document.querySelector(".ck-tiles"),
+ ).gridTemplateColumns.split(" ").length,
+ };
});
+ check(
+ defects.length === 0,
+ `${name}: no chart text leaves its figure or overlaps another (${defects.slice(0, 6).join(" | ")})`,
+ );
+ check(m.overflow <= 0, `${name}: no horizontal scroll (${m.overflow}px over)`);
+ check(m.smallest >= 12, `${name}: no label under 12px (${m.smallest}px)`);
+ check(
+ m.stroke === "2px",
+ `${name}: the line is 2px whatever the plot's size (${m.stroke})`,
+ );
+ check(
+ m.charts >= 8 && m.tables >= 6,
+ `${name}: ${m.charts} charts, ${m.tables} tables behind them`,
+ );
+ check(m.lanes >= 2, `${name}: colliding events took a second lane (${m.lanes} lanes)`);
+ check(m.points === 18, `${name}: every value is a point (${m.points})`);
+ check(
+ m.quiet > 200 && m.quietShown === 0,
+ `${name}: a year of closes draws no dots (${m.quietShown} of ${m.quiet} shown)`,
+ );
+ check(
+ m.quietMinHeight >= 44 && m.quietGap <= 0.5,
+ `${name}: hidden values are full-height strips that tile the plot (${m.quietMinHeight}px tall, gap ${m.quietGap}px)`,
+ );
+ check(
+ m.area === 1 && m.areaFill && m.areaFill !== "none" && m.areaFill !== "rgb(0, 0, 0)",
+ `${name}: area draws one light fill (${m.areaFill})`,
+ );
+ check(m.tileCols === (width < 640 ? 2 : 4), `${name}: tiles ${m.tileCols} across`);
+ check(m.tickInk !== m.ink, `${name}: tick labels in the muted ink, not the text ink`);
+ check(errors.length === 0, `${name}: no page errors ${errors.join(" | ")}`);
+ if (process.env.CHARTKIT_SHOTS) {
+ await page.screenshot({
+ path: `${process.env.CHARTKIT_SHOTS}/demo-${width}-${dark ? "dark" : "light"}-${locale ?? "default"}.png`,
+ fullPage: true,
+ });
+ }
+ await page.close();
}
- await page.close();
}
}
diff --git a/test/core.test.js b/test/core.test.js
index b08fcfc..c3e4c29 100644
--- a/test/core.test.js
+++ b/test/core.test.js
@@ -178,3 +178,23 @@ test("hidden values answer for strips that tile the plot edge to edge, uneven sp
}
assert.deepEqual(hitColumns([{ x: 50, y: 0 }]), [{ left: 0, width: 100 }]);
});
+
+test("localized UTC dates and ticks keep their period and ignore the server timezone", () => {
+ assert.equal(formatX("2025-03-31", "de-DE"), "31. März 2025");
+ assert.equal(formatX("2025-03", "de-DE"), "März 2025");
+ assert.equal(formatX("FY2025", "de-DE"), "FY2025");
+ assert.equal(formatX("2025-Q2", "de-DE"), "Q2 2025");
+ const from = Date.UTC(2025, 1, 1),
+ to = Date.UTC(2025, 3, 1);
+ assert.ok(timeTicks(from, to, 5, "de-DE").some((t) => t.label.includes("März")));
+ assert.ok(
+ monthTicks(from, to, 6, "de-DE").some(
+ (t) =>
+ t.label ===
+ new Intl.DateTimeFormat("de-DE", { month: "short", timeZone: "UTC" }).format(
+ new Date(Date.UTC(2025, 2, 1)),
+ ),
+ ),
+ );
+ assert.ok(numberTicks(1000, 3000, 5, "de-DE").some((t) => t.label === "2.000"));
+});
diff --git a/test/render.test.js b/test/render.test.js
index f37b5aa..d92b7ba 100644
--- a/test/render.test.js
+++ b/test/render.test.js
@@ -376,3 +376,36 @@ test("ColumnChart: periods in the order given, a loss goes down, a gap is a dash
assert.match(html, /--ck-periods:3/);
assert.doesNotMatch(html, /undefined|NaN/);
});
+
+test("localized line, column and timeline charts retain numbers and translate accessible words", () => {
+ const props = {
+ series: [
+ { id: "v", label: "Umsatz", points: [{ x: "2025-03-31", y: 1234.5, preliminary: true }] },
+ ],
+ caption: "Umsatz",
+ locale: "de-DE",
+ periodLabel: "Zeitraum",
+ preliminaryLabel: "vorläufig",
+ };
+ for (const chart of [LineChart, ColumnChart]) {
+ const html = renderToStaticMarkup(h(chart, props));
+ assert.match(html, /Zeitraum/);
+ assert.match(html, /März/);
+ assert.match(html, /1\.234,5/);
+ assert.doesNotMatch(html, />Period);
+ }
+ const line = renderToStaticMarkup(h(LineChart, props));
+ assert.match(line, /vorläufig/);
+ assert.doesNotMatch(line, /preliminary/);
+ const timeline = renderToStaticMarkup(
+ h(Timeline, {
+ events: [{ date: "2025-03-31", label: "Termin" }],
+ caption: "Termine",
+ locale: "de-DE",
+ tableLabels: { date: "Datum", event: "Ereignis", effect: "Wirkung" },
+ }),
+ );
+ assert.match(timeline, /März/);
+ assert.match(timeline, /Datum/);
+ assert.match(timeline, /Ereignis/);
+});