Skip to content

Commit

Permalink
deps(d3): fix updated type issues
Browse files Browse the repository at this point in the history
BREAKING CHANGE: the new d3-scale version used ES2015 and our target version needs to align to that.
  • Loading branch information
markov00 committed May 12, 2022
1 parent 7a5ee49 commit 29804a6
Show file tree
Hide file tree
Showing 13 changed files with 114 additions and 68 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
"@types/d3-cloud": "^1.2.5",
"@types/d3-collection": "^1.0.8",
"@types/d3-interpolate": "^1.3.1",
"@types/d3-scale": "^2.1.1",
"@types/d3-scale": "^4.0.2",
"@types/d3-shape": "^2.0.0",
"@types/enzyme": "^3.9.0",
"@types/enzyme-adapter-react-16": "^1.0.5",
Expand Down
2 changes: 1 addition & 1 deletion packages/charts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"d3-cloud": "^1.2.5",
"d3-collection": "^1.0.7",
"d3-interpolate": "^1.4.0",
"d3-scale": "^2.2.2",
"d3-scale": "^4.0.2",
"d3-shape": "^2.0.0",
"prop-types": "^15.7.2",
"re-reselect": "^3.4.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { ScaleType } from '../../../../scales/constants';
import { LinearScale, OrdinalScale, RasterTimeScale } from '../../../../specs';
import { TextMeasure } from '../../../../utils/bbox/canvas_text_bbox_calculator';
import { addIntervalToTime } from '../../../../utils/chrono/elasticsearch';
import { clamp, Datum } from '../../../../utils/common';
import { clamp, Datum, isDefined } from '../../../../utils/common';
import { innerPad, pad } from '../../../../utils/dimensions';
import { Logger } from '../../../../utils/logger';
import { HeatmapStyle, Theme, Visible } from '../../../../utils/themes/theme';
Expand Down Expand Up @@ -89,7 +89,7 @@ export function shapeViewModel<D extends BaseDatum = Datum>(
.domain([0, elementSizes.grid.width])
.range(xValues);

// compute the cell width (can be smaller then the available size depending on config
// compute the cell width (can be smaller than the available size depending on config
const cellWidth =
heatmapTheme.cell.maxWidth !== 'fill' && xScale.bandwidth() > heatmapTheme.cell.maxWidth
? heatmapTheme.cell.maxWidth
Expand Down Expand Up @@ -129,8 +129,8 @@ export function shapeViewModel<D extends BaseDatum = Datum>(

// compute each available cell position, color and value
const cellMap = table.reduce<Record<string, Cell>>((acc, d) => {
const x = xScale(String(d.x));
const y = yScale(String(d.y))! + gridStrokeWidth;
const x = xScale(d.x);
const y = yScale(d.y);
const yIndex = yValues.indexOf(d.y);

if (x === undefined || y === undefined || yIndex === -1) {
Expand All @@ -156,7 +156,7 @@ export function shapeViewModel<D extends BaseDatum = Datum>(
x:
(heatmapTheme.cell.maxWidth !== 'fill' ? x + xScale.bandwidth() / 2 - heatmapTheme.cell.maxWidth / 2 : x) +
gridStrokeWidth,
y,
y: y + gridStrokeWidth,
yIndex,
width: cellWidthInner,
height: cellHeightInner,
Expand Down Expand Up @@ -230,6 +230,13 @@ export function shapeViewModel<D extends BaseDatum = Datum>(
const endX = xInvertedScale(clamp(bottomRight[0], 0, width));
const startY = yInvertedScale(clamp(topLeft[1], 0, currentGridHeight - 1));
const endY = yInvertedScale(clamp(bottomRight[1], 0, currentGridHeight - 1));
if (!isDefined(startX) || !isDefined(endX) || !isDefined(startY) || !isDefined(endY)) {
return {
cells: [],
x: [],
y: [],
};
}

const allXValuesInRange: Array<NonNullable<PrimitiveValue>> = getValuesInRange(xValues, startX, endX);
const allYValuesInRange: Array<NonNullable<PrimitiveValue>> = getValuesInRange(yValues, startY, endY);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import { PointerEvent } from '../../../../specs';
import { GlobalChartState } from '../../../../state/chart_state';
import { createCustomCachedSelector } from '../../../../state/create_selector';
import { isDefined } from '../../../../utils/common';
import { isValidPointerOverEvent } from '../../../../utils/events';
import { IndexedGeometry } from '../../../../utils/geometry';
import { ChartDimensions } from '../../utils/dimensions';
Expand Down Expand Up @@ -55,13 +56,13 @@ function getElementAtCursorPosition(
return geometriesIndex.find(externalPointerEvent.x, { x: -1, y: -1 });
}
const xValue = scales.xScale.invertWithStep(orientedProjectedPointerPosition.x, geometriesIndexKeys);
if (!xValue) {
if (!isDefined(xValue.value)) {
return [];
}
// get the elements at cursor position
return geometriesIndex
.find(
xValue?.value,
xValue.value,
orientedProjectedPointerPosition,
orientedProjectedPointerPosition.horizontalPanelValue,
orientedProjectedPointerPosition.verticalPanelValue,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { ProjectedValues } from '../../../../specs/settings';
import { createCustomCachedSelector } from '../../../../state/create_selector';
import { isDefined } from '../../../../utils/common';
import { computeSeriesGeometriesSelector } from './compute_series_geometries';
import { getGeometriesIndexKeysSelector } from './get_geometries_index_keys';
import { getOrientedProjectedPointerPositionSelector } from './get_oriented_projected_pointer_position';
Expand All @@ -25,13 +26,13 @@ export const getProjectedScaledValues = createCustomCachedSelector(
}

const xValue = xScale.invertWithStep(x, geometriesIndexKeys);
if (!xValue) {
if (!isDefined(xValue.value)) {
return;
}

return {
x: xValue.value,
y: [...yScales.entries()].map(([groupId, yScale]) => ({ value: yScale.invert(y), groupId })),
y: [...yScales.entries()].map(([groupId, yScale]) => ({ value: yScale.invert(y) ?? NaN, groupId })),
smVerticalValue: verticalPanelValue,
smHorizontalValue: horizontalPanelValue,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ function getXBrushExtent(
const histogramEnabled = isHistogramEnabled(seriesSpecs);
const invertValue =
histogramEnabled && roundHistogramBrushValues
? (value: number) => xScale.invertWithStep(value, xScale.domain).value
: (value: number) => xScale.invert(value);
? (value: number) => xScale.invertWithStep(value, xScale.domain).value ?? NaN
: (value: number) => xScale.invert(value) ?? NaN;
const minPosScaled = invertValue(minPos + offset);
const maxPosScaled = invertValue(maxPos + offset);
const maxDomainValue =
Expand Down Expand Up @@ -210,8 +210,8 @@ function getYBrushExtents(
return;
}

const minPosScaled = yScale.invert(minPos);
const maxPosScaled = yScale.invert(maxPos);
const minPosScaled = yScale.invert(minPos) ?? NaN;
const maxPosScaled = yScale.invert(maxPos) ?? NaN;
const minValue = clamp(minPosScaled, yScale.domain[0], maxPosScaled);
const maxValue = clamp(minPosScaled, maxPosScaled, yScale.domain[1]);
yValues.push({ extent: [minValue, maxValue], groupId });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { GlobalChartState } from '../../../../state/chart_state';
import { createCustomCachedSelector } from '../../../../state/create_selector';
import { getChartIdSelector } from '../../../../state/selectors/get_chart_id';
import { getSettingsSpecSelector } from '../../../../state/selectors/get_settings_specs';
import { isDefined } from '../../../../utils/common';
import { ComputedScales } from '../utils/types';
import { computeSeriesGeometriesSelector } from './compute_series_geometries';
import { getGeometriesIndexKeysSelector } from './get_geometries_index_keys';
Expand Down Expand Up @@ -47,7 +48,7 @@ function getPointerEvent(
return { chartId, type: PointerEventType.Out };
}
const xValue = xScale.invertWithStep(x, geometriesIndexKeys);
if (!xValue) {
if (!isDefined(xValue.value)) {
return { chartId, type: PointerEventType.Out };
}
return {
Expand All @@ -57,7 +58,7 @@ function getPointerEvent(
scale: xScale.type,
x: xValue.value,
y: [...yScales.entries()].map(([groupId, yScale]) => {
return { value: yScale.invert(y), groupId };
return { value: yScale.invert(y) ?? NaN, groupId };
}),
smVerticalValue: verticalPanelValue,
smHorizontalValue: horizontalPanelValue,
Expand Down
6 changes: 3 additions & 3 deletions packages/charts/src/scales/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export type ScaleBandType = ScaleOrdinalType;
/**
* A `Scale` interface. A scale can map an input value within a specified domain
* to an output value from a specified range.
* The the value is mapped depending on the `type` (linear, log, sqrt, time, ordinal)
* The value is mapped depending on the `type` (linear, log, sqrt, time, ordinal)
* @internal
*/
export interface Scale<T> {
Expand All @@ -39,12 +39,12 @@ export interface Scale<T> {
ticks: () => T[];
scale: (value?: PrimitiveValue) => number;
pureScale: (value?: PrimitiveValue) => number;
invert: (value: number) => T;
invert: (value: number) => T | undefined;
invertWithStep: (
value: number,
data: any[],
) => {
value: T;
value: T | undefined;
withinBandwidth: boolean;
};
isSingleValue: () => boolean;
Expand Down
6 changes: 3 additions & 3 deletions packages/charts/src/scales/scale_band.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ import { Scale, ScaleBandType } from '.';
import { PrimitiveValue } from '../chart_types/partition_chart/layout/utils/group_by_rollup';
import { Ratio } from '../common/geometry';
import { RelativeBandsPadding } from '../specs';
import { clamp, stringifyNullsUndefined } from '../utils/common';
import { clamp } from '../utils/common';
import { Range } from '../utils/domain';
import { ScaleType } from './constants';

/**
* Categorical scale
* @internal
*/
export class ScaleBand<T extends number | string> implements Scale<T> {
export class ScaleBand<T extends number | string | undefined> implements Scale<T> {
readonly bandwidth: number;

readonly bandwidthPadding: number;
Expand Down Expand Up @@ -85,7 +85,7 @@ export class ScaleBand<T extends number | string> implements Scale<T> {
}

scale(value?: PrimitiveValue) {
const scaleValue = this.d3Scale(stringifyNullsUndefined(value));
const scaleValue = this.d3Scale((value as unknown) as T);
return typeof scaleValue === 'number' && Number.isFinite(scaleValue) ? scaleValue : NaN; // fixme when TS improves
}

Expand Down
19 changes: 15 additions & 4 deletions packages/charts/src/scales/scale_continuous.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
ScaleLogarithmic,
ScalePower,
scaleSqrt,
ScaleTime,
scaleUtc,
} from 'd3-scale';
import { Required } from 'utility-types';
Expand All @@ -29,7 +30,15 @@ import { ContinuousDomain, Range } from '../utils/domain';
import { LOG_MIN_ABS_DOMAIN, ScaleType } from './constants';
import { LogScaleOptions } from './types';

const SCALES = {
type ContinuousScaleType =
| typeof ScaleType.Time
| typeof ScaleType.Linear
| typeof ScaleType.Log
| typeof ScaleType.Sqrt;
const SCALES: Record<
ContinuousScaleType,
() => ScaleContinuousNumeric<number, number, undefined> | ScaleTime<number, number, undefined>
> = {
[ScaleType.Linear]: scaleLinear,
[ScaleType.Log]: scaleLog,
[ScaleType.Sqrt]: scaleSqrt,
Expand Down Expand Up @@ -70,7 +79,7 @@ export class ScaleContinuous implements Scale<number> {
readonly timeZone: string;
readonly barsPadding: number;
readonly isSingleValueHistogram: boolean;
private readonly project: (d: number) => number;
private readonly project: (d: number) => number | undefined;
private readonly inverseProject: (d: number) => number | Date;

constructor(
Expand Down Expand Up @@ -171,12 +180,14 @@ export class ScaleContinuous implements Scale<number> {

scale(value?: PrimitiveValue) {
return typeof value === 'number'
? this.project(value) + (this.bandwidthPadding / 2) * this.totalBarsInCluster
? (this.project(value) ?? NaN) + (this.bandwidthPadding / 2) * this.totalBarsInCluster
: NaN;
}

pureScale(value?: PrimitiveValue) {
return typeof value === 'number' ? this.project(this.bandwidth === 0 ? value : value + this.minInterval / 2) : NaN;
return typeof value === 'number'
? this.project(this.bandwidth === 0 ? value : value + this.minInterval / 2) ?? NaN
: NaN;
}

ticks() {
Expand Down
2 changes: 1 addition & 1 deletion packages/charts/src/scales/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { ScaleBand } from './scale_band';
import { ScaleContinuous } from './scale_continuous';

/**
* Check if a scale is logaritmic
* Check if a scale is logarithmic
* @internal
*/
export function isLogarithmicScale(scale: Scale<number | string>): scale is ScaleContinuous {
Expand Down
13 changes: 0 additions & 13 deletions packages/charts/src/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,19 +446,6 @@ export function getDistance(a: Point, b: Point): number {
return Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));
}

/** @internal */
export function stringifyNullsUndefined(value?: PrimitiveValue): string | number {
if (value === undefined) {
return 'undefined';
}

if (value === null) {
return 'null';
}

return value;
}

/**
* Determines if an array has all unique values
*
Expand Down
Loading

0 comments on commit 29804a6

Please sign in to comment.