File size: 8,574 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import { useMemo, useRef, useEffect } from 'react'
import { line } from 'd3-shape'
import { scaleLinear, scalePoint } from 'd3-scale'
import { curveFromProp } from '@nivo/core'
import { OrdinalColorScaleConfig, useOrdinalColorScale } from '@nivo/colors'
import { castPointScale, castLinearScale, ScalePoint } from '@nivo/scales'
import {
    Variable,
    VariableWithScale,
    CommonProps,
    ComputedDatum,
    BaseDatum,
    BaseGroup,
    Group,
    CustomLayerProps,
    GroupLegend,
    DatumLegend,
    DatumGroupKeys,
    IfGrouped,
    ComputedGroupDatum,
} from './types'
import { commonDefaultProps } from './defaults'

/**
 * Compute groups.
 *
 * Please note that we assume that `groupBy` is defined, and correct, at this stage.
 *
 * If `predefinedGroups` is provided, we'll use it as a base, otherwise
 * we're going to scan each datum and extract their group, and then
 * make those unique to define the available groups.
 */
const computeGroups = <Datum extends BaseDatum>({
    data,
    groupBy,
    predefinedGroups,
    getColor,
}: {
    data: readonly Datum[]
    groupBy: DatumGroupKeys<Datum>
    predefinedGroups?: readonly BaseGroup[]
    getColor: (group: BaseGroup) => string
}): Group[] => {
    let groups: Group[]

    if (predefinedGroups !== undefined) {
        groups = predefinedGroups.map(group => ({
            id: group.id,
            label: group.label || group.id,
            color: getColor(group),
        }))
    } else {
        const groupsSet = new Set<string>()
        for (const datum of data) {
            groupsSet.add(datum[groupBy] as string)
        }

        groups = Array.from(groupsSet, groupId => {
            const group: BaseGroup = {
                id: groupId,
                label: groupId,
            }

            return {
                ...group,
                color: getColor(group),
            }
        })
    }

    return groups
}

/**
 * Compute the scale for each variable.
 *
 * We only support linear scales.
 *
 * Each scale domain will be computed automatically if `min`/`max` = `'auto'`,
 * otherwise, we'll use the provided values.
 */
const computeVariablesScales = <Datum extends BaseDatum>({
    width,
    height,
    data,
    variables,
    layout,
}: {
    width: number
    height: number
    data: readonly Datum[]
    variables: readonly Variable<Datum>[]
    layout: CommonProps<Datum>['layout']
}): readonly VariableWithScale<Datum>[] => {
    // Depending on the layout, the range might need to be switched.
    const range = layout === 'horizontal' ? [height, 0] : [0, width]

    return variables.map(variable => {
        const allValues: number[] = data.map(datum => datum[variable.value] as number)

        const min =
            variable.min !== undefined && variable.min !== 'auto'
                ? variable.min
                : Math.min(...allValues!)
        const max =
            variable.max !== undefined && variable.max !== 'auto'
                ? variable.max
                : Math.max(...allValues!)

        const scale = castLinearScale(scaleLinear().rangeRound(range).domain([min, max]))

        return { ...variable, scale }
    })
}

const computeDataVariables = <Datum extends BaseDatum>({
    data,
    groupBy,
    groups,
    variablesScale,
    variablesWithScale,
    layout,
    getColor,
}: {
    data: readonly Datum[]
    groupBy?: DatumGroupKeys<Datum>
    groups: Group[] | undefined
    variablesScale: ScalePoint<string>
    variablesWithScale: readonly VariableWithScale<Datum>[]
    layout: CommonProps<Datum>['layout']
    getColor: (datum: Datum) => string
}): ComputedDatum<Datum>[] | ComputedGroupDatum<Datum>[] => {
    return data.map((datum, index) => {
        const points: [number, number][] = variablesWithScale.map(variable => [
            layout === 'horizontal'
                ? variablesScale(variable.id)!
                : variable.scale(datum[variable.value] as number),
            layout === 'horizontal'
                ? variable.scale(datum[variable.value] as number)
                : variablesScale(variable.id)!,
        ])

        let group: Group | undefined = undefined
        if (groupBy !== undefined) {
            const datumGroup = datum[groupBy]
            group = groups?.find(candidateGroup => candidateGroup.id === datumGroup)
        }

        const computedDatum: ComputedDatum<Datum> = {
            id: datum.id,
            index,
            points,
            data: datum,
            color: group ? group.color : getColor(datum),
        }

        if (!group) return computedDatum

        return {
            ...computedDatum,
            group,
        } as ComputedGroupDatum<Datum>
    })
}

export const useParallelCoordinates = <
    Datum extends BaseDatum,
    GroupBy extends DatumGroupKeys<Datum> | undefined = undefined,
>({
    width,
    height,
    data,
    variables,
    groupBy,
    groups: predefinedGroups,
    layout = commonDefaultProps.layout,
    curve = commonDefaultProps.curve,
    colors = commonDefaultProps.colors as OrdinalColorScaleConfig<
        IfGrouped<Datum, GroupBy, BaseGroup, Datum>
    >,
    forwardLegendData,
}: {
    width: number
    height: number
    data: readonly Datum[]
    variables: readonly Variable<Datum>[]
    groupBy?: CommonProps<Datum, GroupBy>['groupBy']
    groups?: CommonProps<Datum, GroupBy>['groups']
    layout: CommonProps<Datum, GroupBy>['layout']
    curve: CommonProps<Datum, GroupBy>['curve']
    colors: CommonProps<Datum, GroupBy>['colors']
    forwardLegendData?: CommonProps<Datum, GroupBy>['forwardLegendData']
}) => {
    // If no groups, we'll use the data to define the color, otherwise the groups,
    // meaning that `id` refers to either `Datum.id` or `Group.id`.
    const getColor = useOrdinalColorScale(colors, 'id')

    const groups = useMemo(() => {
        if (groupBy === undefined) return undefined

        return computeGroups<Datum>({
            data,
            groupBy,
            predefinedGroups,
            getColor: getColor as (group: BaseGroup) => string,
        })
    }, [data, groupBy, predefinedGroups, getColor])

    const variablesScale = useMemo(() => {
        const variableIds = variables.map(({ id }) => id)
        return castPointScale(
            scalePoint()
                .range(layout === 'horizontal' ? [0, width] : [height, 0])
                .domain(variableIds)
        )
    }, [variables, layout, width, height])

    const variablesWithScale = useMemo(
        () =>
            computeVariablesScales<Datum>({
                width,
                height,
                data,
                variables,
                layout,
            }),
        [width, height, data, variables, layout]
    )

    const computedData = useMemo(
        () =>
            computeDataVariables<Datum>({
                data,
                groupBy,
                groups,
                variablesScale,
                variablesWithScale,
                layout,
                getColor,
            }),
        [data, groupBy, groups, variablesScale, variablesWithScale, layout, getColor]
    )

    const legendData = useMemo(() => {
        if (!groups) {
            return computedData.map(datum => ({
                id: datum.id,
                label: datum.id,
                color: datum.color,
                data: datum,
            })) as DatumLegend<Datum>[]
        }

        return groups.map(group => ({
            id: group.id,
            label: group.label || group.id,
            color: group.color,
            data: group,
        })) as GroupLegend[]
    }, [groups, computedData])

    // Forward the legends data if `forwardLegendData` is defined.
    const forwardLegendDataRef = useRef(forwardLegendData)
    useEffect(() => {
        if (typeof forwardLegendDataRef.current !== 'function') return
        forwardLegendDataRef.current(
            legendData as IfGrouped<Datum, GroupBy, GroupLegend[], DatumLegend<Datum>[]>
        )
    }, [forwardLegendDataRef, legendData])

    const lineGenerator = useMemo(
        () => line<[number, number]>().curve(curveFromProp(curve)),
        [curve]
    )

    const customLayerContext: CustomLayerProps<Datum> = useMemo(
        () => ({
            computedData,
            variables,
            lineGenerator,
        }),
        [computedData, variables, lineGenerator]
    )

    return {
        variablesScale,
        variablesWithScale,
        computedData,
        lineGenerator,
        legendData,
        customLayerContext,
    }
}