From c3416c43c5b4035cb8e1025370939f635a272084 Mon Sep 17 00:00:00 2001 From: Axel Bocciarelli Date: Wed, 5 Feb 2025 15:26:34 +0100 Subject: [PATCH] Allow passing custom axis tick formatters to `VisCanvas` --- apps/storybook/src/VisCanvas.stories.tsx | 18 ++++++++++++++++++ packages/lib/src/vis/models.ts | 1 + packages/lib/src/vis/shared/Axis.tsx | 5 ++++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/apps/storybook/src/VisCanvas.stories.tsx b/apps/storybook/src/VisCanvas.stories.tsx index 2651b33e6..7483cdf61 100644 --- a/apps/storybook/src/VisCanvas.stories.tsx +++ b/apps/storybook/src/VisCanvas.stories.tsx @@ -1,5 +1,6 @@ import { ScaleType, VisCanvas } from '@h5web/lib'; import { type Meta, type StoryFn, type StoryObj } from '@storybook/react'; +import { format } from 'd3-format'; import FillHeight from './decorators/FillHeight'; @@ -34,6 +35,23 @@ export const NiceDomains = { }, } satisfies Story; +export const TickFormatters = { + args: { + abscissaConfig: { + visDomain: [-1.2, 2.8], + showGrid: true, + formatTick: (val) => { + return Math.round(val) === val ? val.toString() : val.toFixed(3); + }, + }, + ordinateConfig: { + visDomain: [50, 100], + showGrid: true, + formatTick: format('.2e'), + }, + }, +} satisfies Story; + export const LogScales = { args: { abscissaConfig: { diff --git a/packages/lib/src/vis/models.ts b/packages/lib/src/vis/models.ts index 9efe8ca05..be53b0aee 100644 --- a/packages/lib/src/vis/models.ts +++ b/packages/lib/src/vis/models.ts @@ -42,6 +42,7 @@ export interface AxisConfig { label?: string; flip?: boolean; nice?: boolean; + formatTick?: (val: number) => string; } export type VisScaleType = ColorScaleType | [ScaleType.Gamma, number]; diff --git a/packages/lib/src/vis/shared/Axis.tsx b/packages/lib/src/vis/shared/Axis.tsx index b8342f56b..545f7a85a 100644 --- a/packages/lib/src/vis/shared/Axis.tsx +++ b/packages/lib/src/vis/shared/Axis.tsx @@ -49,6 +49,7 @@ function Axis(props: Props) { showGrid, label, nice = false, + formatTick, } = config; // Restrain ticks scales to visible domains const scale = createScale(scaleType, { @@ -76,7 +77,9 @@ function Axis(props: Props) { >