Skip to content

Commit

Permalink
case independent scale type matching (observablehq#1904)
Browse files Browse the repository at this point in the history
* case independent scale type matching

closes observablehq#1894

* normalize type in inferScaleType

---------

Co-authored-by: Mike Bostock <mbostock@gmail.com>
  • Loading branch information
2 people authored and chaichontat committed Jan 14, 2024
1 parent 61f4410 commit 5b057a9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/scales.js
Original file line number Diff line number Diff line change
Expand Up @@ -376,10 +376,16 @@ function formatScaleType(type) {
return typeof type === "symbol" ? type.description : type;
}

function maybeScaleType(type) {
return typeof type === "string" ? `${type}`.toLowerCase() : type;
}

// A special type symbol when the x and y scales are replaced with a projection.
const typeProjection = {toString: () => "projection"};

function inferScaleType(key, channels, {type, domain, range, scheme, pivot, projection}) {
type = maybeScaleType(type);

// The facet scales are always band scales; this cannot be changed.
if (key === "fx" || key === "fy") return "band";

Expand All @@ -391,7 +397,8 @@ function inferScaleType(key, channels, {type, domain, range, scheme, pivot, proj
// If a channel dictates a scale type, make sure that it is consistent with
// the user-specified scale type (if any) and all other channels. For example,
// barY requires x to be a band scale and disallows any other scale type.
for (const {type: t} of channels) {
for (const channel of channels) {
const t = maybeScaleType(channel.type);
if (t === undefined) continue;
else if (type === undefined) type = t;
else if (type !== t) throw new Error(`scale incompatible with channel: ${type} !== ${t}`);
Expand Down
6 changes: 6 additions & 0 deletions test/scales/scales-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ it("Plot does not throw an error if a quantile scale has a non-monotonic domain"
});
});

it("Scale types are lowercased", () => {
assert.strictEqual(Plot.scale({x: {type: "UTC"}}).type, "utc");
assert.strictEqual(Plot.scale({color: {type: "OrDiNaL"}}).type, "ordinal");
assert.strictEqual(Plot.scale({fx: {type: "BAND"}}).type, "band");
});

it("Plot.scale(description) returns a standalone scale", () => {
const color = Plot.scale({color: {type: "linear"}});
scaleEqual(color, {
Expand Down

0 comments on commit 5b057a9

Please sign in to comment.