Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: graceful scale fallbacks and warnings #704

Merged
merged 5 commits into from
Jun 15, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/chart_types/xy_chart/domains/x_domain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,61 @@ describe('X Domain', () => {
);
expect(mergedDomain.domain).toEqual([0, 1, 2, 5, 7]);
});

test('Should fallback to ordinal scale if not array of numbers', () => {
const ds1: BasicSeriesSpec = {
chartType: ChartTypes.XYAxis,
specType: SpecTypes.Series,
id: 'ds1',
groupId: 'g1',
seriesType: SeriesTypes.Bar,
xAccessor: 'x',
yAccessors: ['y'],
xScaleType: ScaleType.Linear,
yScaleType: ScaleType.Linear,
yScaleToDataExtent: false,
data: [
{ x: 0, y: 0 },
{ x: 'a', y: 0 },
{ x: 2, y: 0 },
{ x: 5, y: 0 },
],
};
const ds2: BasicSeriesSpec = {
chartType: ChartTypes.XYAxis,
specType: SpecTypes.Series,
id: 'ds2',
groupId: 'g2',
seriesType: SeriesTypes.Bar,
xAccessor: 'x',
yAccessors: ['y'],
xScaleType: ScaleType.Linear,
yScaleType: ScaleType.Linear,
yScaleToDataExtent: false,
data: [
{ x: 0, y: 0 },
{ x: 7, y: 0 },
],
};
const specDataSeries = [ds1, ds2];

const { xValues } = getSplittedSeries(specDataSeries);
const mergedDomain = mergeXDomain(
[
{
seriesType: SeriesTypes.Bar,
xScaleType: ScaleType.Linear,
},
{
seriesType: SeriesTypes.Bar,
xScaleType: ScaleType.Ordinal,
},
],
xValues,
);
expect(mergedDomain.domain).toEqual([0, 'a', 2, 5, 7]);
expect(mergedDomain.scaleType).toEqual(ScaleType.Ordinal);
});
test('Should merge multi bar/line ordinal series correctly', () => {
const ds1: BasicSeriesSpec = {
chartType: ChartTypes.XYAxis,
Expand Down
16 changes: 13 additions & 3 deletions src/chart_types/xy_chart/domains/x_domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export function mergeXDomain(
specs: Pick<BasicSeriesSpec, 'seriesType' | 'xScaleType'>[],
xValues: Set<string | number>,
customXDomain?: DomainRange | Domain,
fallbackScale?: ScaleType,
): XDomain {
const mainXScaleType = convertXScaleTypes(specs);
if (!mainXScaleType) {
Expand All @@ -46,7 +47,14 @@ export function mergeXDomain(
let seriesXComputedDomains;
let minInterval = 0;

if (mainXScaleType.scaleType === ScaleType.Ordinal) {
if (mainXScaleType.scaleType === ScaleType.Ordinal || fallbackScale === ScaleType.Ordinal) {
if (mainXScaleType.scaleType !== ScaleType.Ordinal) {
// eslint-disable-next-line no-console
console.warn(
markov00 marked this conversation as resolved.
Show resolved Hide resolved
`Each X value in a ${mainXScaleType.scaleType} x scale needs be be a number. Using ordinal x scale as fallback.`,
);
}

seriesXComputedDomains = computeOrdinalDataDomain(values, identity, false, true);
if (customXDomain) {
if (Array.isArray(customXDomain)) {
Expand All @@ -58,7 +66,9 @@ export function mergeXDomain(
} else {
seriesXComputedDomains = computeContinuousDataDomain(values, identity, true);
let customMinInterval: undefined | number;
if (!isNumberArray(values)) {

// The number check is done in mergeXDomain which makes this a dummy type check
if (!isNumberArray(values, !fallbackScale)) {
markov00 marked this conversation as resolved.
Show resolved Hide resolved
throw new Error(
`Each X value in a ${mainXScaleType.scaleType} x scale needs be be a number. String or objects are not allowed`,
);
Expand Down Expand Up @@ -107,7 +117,7 @@ export function mergeXDomain(

return {
type: 'xDomain',
scaleType: mainXScaleType.scaleType,
scaleType: fallbackScale ?? mainXScaleType.scaleType,
isBandScale: mainXScaleType.isBandScale,
domain: seriesXComputedDomains,
minInterval,
Expand Down
10 changes: 6 additions & 4 deletions src/chart_types/xy_chart/state/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,15 @@ export function computeSeriesDomains(
deselectedDataSeries: SeriesIdentifier[] = [],
customXDomain?: DomainRange | Domain,
): SeriesDomainsAndData {
const { splittedSeries, xValues, seriesCollection } = deselectedDataSeries
? getSplittedSeries(seriesSpecs, deselectedDataSeries)
: getSplittedSeries(seriesSpecs, []);
const {
splittedSeries,
xValues, seriesCollection,
fallbackScale,
} = getSplittedSeries(seriesSpecs, deselectedDataSeries);
const splittedDataSeries = [...splittedSeries.values()];
const specsArray = [...seriesSpecs.values()];

const xDomain = mergeXDomain(specsArray, xValues, customXDomain);
const xDomain = mergeXDomain(specsArray, xValues, customXDomain, fallbackScale);
const yDomain = mergeYDomain(splittedSeries, specsArray, customYDomainsByGroupId);

const formattedDataSeries = getFormattedDataseries(
Expand Down
10 changes: 5 additions & 5 deletions src/chart_types/xy_chart/utils/series.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -683,26 +683,26 @@ describe('Series', () => {
expect(getSortedDataSeriesColorsValuesMap(seriesCollection)).toEqual(undefinedSortedColorValues);
});
test('clean datum shall parse string as number for y values', () => {
let datum = cleanDatum([0, 1, 2], 0, 1, 2);
let datum = cleanDatum([0, 1, 2], 0, 1, [], 2);
expect(datum).toBeDefined();
expect(datum?.y1).toBe(1);
expect(datum?.y0).toBe(2);
datum = cleanDatum([0, '1', 2], 0, 1, 2);
datum = cleanDatum([0, '1', 2], 0, 1, [], 2);
expect(datum).toBeDefined();
expect(datum?.y1).toBe(1);
expect(datum?.y0).toBe(2);

datum = cleanDatum([0, '1', '2'], 0, 1, 2);
datum = cleanDatum([0, '1', '2'], 0, 1, [], 2);
expect(datum).toBeDefined();
expect(datum?.y1).toBe(1);
expect(datum?.y0).toBe(2);

datum = cleanDatum([0, 1, '2'], 0, 1, 2);
datum = cleanDatum([0, 1, '2'], 0, 1, [], 2);
expect(datum).toBeDefined();
expect(datum?.y1).toBe(1);
expect(datum?.y0).toBe(2);

datum = cleanDatum([0, 'invalid', 'invalid'], 0, 1, 2);
datum = cleanDatum([0, 'invalid', 'invalid'], 0, 1, [], 2);
expect(datum).toBeDefined();
expect(datum?.y1).toBe(null);
expect(datum?.y0).toBe(null);
Expand Down
41 changes: 35 additions & 6 deletions src/chart_types/xy_chart/utils/series.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export function splitSeries({
const series = new Map<SeriesKey, RawDataSeries>();
const colorsValues = new Set<string>();
const xValues = new Set<string | number>();
const nonNumericValues: any[] = [];

data.forEach((datum) => {
const splitAccessors = getSplitAccessors(datum, splitSeriesAccessors);
Expand All @@ -164,6 +165,7 @@ export function splitSeries({
datum,
xAccessor,
accessor,
nonNumericValues,
y0Accessors && y0Accessors[index],
markSizeAccessor,
);
Expand All @@ -175,7 +177,14 @@ export function splitSeries({
}
});
} else {
const cleanedDatum = cleanDatum(datum, xAccessor, yAccessors[0], y0Accessors && y0Accessors[0], markSizeAccessor);
const cleanedDatum = cleanDatum(
datum,
xAccessor,
yAccessors[0],
nonNumericValues,
markov00 marked this conversation as resolved.
Show resolved Hide resolved
y0Accessors && y0Accessors[0],
markSizeAccessor,
);
if (cleanedDatum !== null && cleanedDatum.x !== null && cleanedDatum.x !== undefined) {
xValues.add(cleanedDatum.x);
const seriesKey = updateSeriesMap(series, splitAccessors, yAccessors[0], cleanedDatum, specId);
Expand All @@ -184,6 +193,13 @@ export function splitSeries({
}
});

if (nonNumericValues.length > 0) {
// eslint-disable-next-line no-console
console.warn(`Found non-numeric y value${nonNumericValues.length > 1 ? 's' : ''} in dataset for spec "${specId}"`,
`(${nonNumericValues.map((v) => JSON.stringify(v)).join(', ')})`
);
}

return {
rawDataSeries: [...series.values()],
colorsValues,
Expand Down Expand Up @@ -266,6 +282,7 @@ export function cleanDatum(
datum: Datum,
xAccessor: Accessor | AccessorFn,
yAccessor: Accessor,
nonNumericValues: any[],
y0Accessor?: Accessor,
markSizeAccessor?: Accessor | AccessorFn,
): RawDataSeriesDatum | null {
Expand All @@ -280,20 +297,26 @@ export function cleanDatum(
}

const mark = markSizeAccessor === undefined ? null : getAccessorValue(datum, markSizeAccessor);
const y1 = castToNumber(datum[yAccessor]);
const y1 = castToNumber(datum[yAccessor], nonNumericValues);
const cleanedDatum: RawDataSeriesDatum = { x, y1, datum, y0: null, mark };
if (y0Accessor) {
cleanedDatum.y0 = castToNumber(datum[y0Accessor as keyof typeof datum]);
cleanedDatum.y0 = castToNumber(datum[y0Accessor as keyof typeof datum], nonNumericValues);
}
return cleanedDatum;
}

function castToNumber(value: any): number | null {
function castToNumber(value: any, nonNumericValues: any[]): number | null {
if (value === null || value === undefined) {
return null;
}
const num = Number(value);
return isNaN(num) ? null : num;

if (isNaN(num)) {
nonNumericValues.push(value);

return null;
}
return num;
}

/** @internal */
Expand Down Expand Up @@ -406,10 +429,12 @@ export function getSplittedSeries(
splittedSeries: Map<SpecId, RawDataSeries[]>;
seriesCollection: Map<SeriesKey, SeriesCollectionValue>;
xValues: Set<string | number>;
fallbackScale?: ScaleType;
} {
const splittedSeries = new Map<SpecId, RawDataSeries[]>();
const seriesCollection = new Map<SeriesKey, SeriesCollectionValue>();
const xValues: Set<any> = new Set();
let isNumberArray = true;
let isOrdinalScale = false;
// eslint-disable-next-line no-restricted-syntax
for (const spec of seriesSpecs) {
Expand Down Expand Up @@ -437,6 +462,9 @@ export function getSplittedSeries(

// eslint-disable-next-line no-restricted-syntax
for (const xValue of dataSeries.xValues) {
if (isNumberArray && typeof xValue !== 'number') {
isNumberArray = false;
}
xValues.add(xValue);
}
}
Expand All @@ -445,7 +473,8 @@ export function getSplittedSeries(
splittedSeries,
seriesCollection,
// keep the user order for ordinal scales
xValues: isOrdinalScale ? xValues : new Set([...xValues].sort()),
xValues: (isOrdinalScale || !isNumberArray) ? xValues : new Set([...xValues].sort()),
fallbackScale: (!isOrdinalScale && !isNumberArray) ? ScaleType.Ordinal : undefined,
};
}

Expand Down
4 changes: 2 additions & 2 deletions src/utils/commons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,8 +327,8 @@ export function mergePartial<T>(
}

/** @internal */
export function isNumberArray(value: unknown): value is number[] {
return Array.isArray(value) && value.every((element) => typeof element === 'number');
export function isNumberArray(value: unknown, bypass?: boolean): value is number[] {
return bypass ?? (Array.isArray(value) && value.every((element) => typeof element === 'number'));
}

/** @internal */
Expand Down