From bd859a5c7f2ab7fb740d8223011e1b5403f5c327 Mon Sep 17 00:00:00 2001 From: Mike Bostock Date: Thu, 14 Nov 2024 09:12:45 -0800 Subject: [PATCH] fix tickFormat type inference for empty domain --- src/marks/axis.js | 4 ++-- src/scales.js | 8 ++++---- test/plots/index.ts | 1 + test/plots/tick-format.ts | 5 +++++ 4 files changed, 12 insertions(+), 6 deletions(-) create mode 100644 test/plots/tick-format.ts diff --git a/src/marks/axis.js b/src/marks/axis.js index 7c7944a55f..3a0e644909 100644 --- a/src/marks/axis.js +++ b/src/marks/axis.js @@ -672,10 +672,10 @@ export function inferTickFormat(scale, data, ticks, tickFormat, anchor) { ? inferTimeFormat(scale.type, data, anchor) ?? formatDefault : scale.tickFormat ? scale.tickFormat(typeof ticks === "number" ? ticks : null, tickFormat) + : typeof tickFormat === "string" && scale.domain().length > 0 + ? (isTemporal(scale.domain()) ? utcFormat : format)(tickFormat) : tickFormat === undefined ? formatDefault - : typeof tickFormat === "string" - ? (isTemporal(scale.domain()) ? utcFormat : format)(tickFormat) : constant(tickFormat); } diff --git a/src/scales.js b/src/scales.js index 46a1f45c3c..f5be6d9f29 100644 --- a/src/scales.js +++ b/src/scales.js @@ -425,10 +425,10 @@ function inferScaleType(key, channels, {type, domain, range, scheme, pivot, proj if (kind === opacity || kind === length) return "linear"; if (kind === symbol) return "ordinal"; - // If the domain or range has more than two values, assume it’s ordinal. You - // can still use a “piecewise” (or “polylinear”) scale, but you must set the - // type explicitly. - if ((domain || range || []).length > 2) return asOrdinalType(kind); + // If the domain or range doesn’t have exactly two values, assume it’s + // ordinal. You can still use a “piecewise” (or “polylinear”) scale, but you + // must set the type explicitly. + if ((domain || range || []).length !== 2) return asOrdinalType(kind); // Otherwise, infer the scale type from the data! Prefer the domain, if // present, over channels. (The domain and channels should be consistently diff --git a/test/plots/index.ts b/test/plots/index.ts index b13d1ec45b..f8e3a09805 100644 --- a/test/plots/index.ts +++ b/test/plots/index.ts @@ -308,6 +308,7 @@ export * from "./style-overrides.js"; export * from "./symbol-set.js"; export * from "./text-overflow.js"; export * from "./this-is-just-to-say.js"; +export * from "./tick-format.js"; export * from "./time-axis.js"; export * from "./tip-format.js"; export * from "./tip.js"; diff --git a/test/plots/tick-format.ts b/test/plots/tick-format.ts new file mode 100644 index 0000000000..3cccb52d27 --- /dev/null +++ b/test/plots/tick-format.ts @@ -0,0 +1,5 @@ +import * as Plot from "@observablehq/plot"; + +export async function tickFormatEmptyDomain() { + return Plot.plot({y: {tickFormat: "%W"}, marks: [Plot.dotX([0]), Plot.barY([]), Plot.frame()]}); +}