TimelineChart.jsx 11.5 KB
Newer Older
amarcic's avatar
amarcic committed
1
2
3
import React, {useEffect, useRef, useState} from "react";
import { useTranslation } from "react-i18next";
import { useStyles } from "../../styles";
amarcic's avatar
amarcic committed
4
import { select, scaleBand, axisBottom, scaleLinear, zoom } from "d3";
amarcic's avatar
amarcic committed
5
6
7
8
9
10
11
import {getTimeRangeOfTimelineData, newGroupByPeriods} from "../../utils";

export const TimelineChart = (props) => {
    const { t, i18n } = useTranslation();

    const classes = useStyles();

12
13
14
    const svgRef = useRef();

    //const filteredTimelineData = props.filteredTimelineData;
15
    console.log("dimensions", props.dimensions)
16
17
18
19
    const xDomain = getTimeRangeOfTimelineData(props.filteredTimelineData,"period");
    const data = newGroupByPeriods(props.filteredTimelineData);

    const timelineData = { xDomain, data, svgRef };
amarcic's avatar
amarcic committed
20

amarcic's avatar
amarcic committed
21
    //console.log(timelineObjectsData);
22
    console.log("filteredTimelineData: ", props.filteredTimelineData);
amarcic's avatar
amarcic committed
23
24
25

    //setting up the svg after first render
    useEffect(() => {
26
        const { width, height, margin } = props.dimensions;
27
        //console.log("width", width)
amarcic's avatar
amarcic committed
28
29
30
31
32
33
        const svg = select(svgRef.current)
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom);
        svg.select('.timelineGroup')
            .attr("transform",`translate(${margin.left}, ${margin.top})`);

34
    }, [props.dimensions]);
amarcic's avatar
amarcic committed
35

36
    //draw timeline everytime filteredTimelineData changes
amarcic's avatar
amarcic committed
37
    useEffect( () => {
38
39
        drawTimeline(timelineData, props.dimensions)
    }, [props.filteredTimelineData, props.dimensions] );
amarcic's avatar
amarcic committed
40

41
//todo: still depending on outer scope for height, width, margin
42
    const drawTimeline = (timelineConfig, dimensions) => {
43
44

        const { data, svgRef, xDomain } = timelineConfig;
45
        const { width, height, margin } = dimensions;
46
        const svg = select(svgRef.current);
47

48
49
50
51
52
        if(!data||data.size===0) {
            svg.selectAll(".bar").remove();
            svg.selectAll(".label").remove();
            return;
        }
amarcic's avatar
amarcic committed
53
54
        //console.log([...data.values()]);

amarcic's avatar
amarcic committed
55
        const selection = svg.select(".timelineGroup").selectAll("rect").data([...data.values()], data => data.periodId);
56
        //console.log("initial selection", selection);
57
        const selectionLabels = svg.select(".timelineGroup").selectAll(".label").data([...data.values()], data => data.periodId);
amarcic's avatar
amarcic committed
58
        const periodIds = [...data.keys()];
59

amarcic's avatar
amarcic committed
60
61
62
63
64
65
66
67
68
69
        //scale for the x axis
        const xScale = scaleLinear()
            .domain(xDomain)
            .range([0,width])
        //scale for the y axis
        const yScale = scaleBand()
            .domain(periodIds)
            .range([height,0])
            .padding(0.2)

70
71
72
73
74
75
        //add x axis to svg
        const xAxis = axisBottom(xScale);
        const xAxisDraw = svg.select(".xAxis")
            .attr("transform", `translate(0,${height})`)
            .call(xAxis);

amarcic's avatar
amarcic committed
76
77
        //set up zoom and pan
        const handleZoom = (event) => {
78
79
80
81
82
83
84

            const transform = event.transform;
            //zoom and pan bars (geometric)
            svg.select(".timelineGroup").selectAll(".bar")
                .attr("transform", transform);

            const xScaleNew = transform.rescaleX(xScale);
85
            const yScaleNew = yScale.range([height,0].map( d => transform.applyY(d) ));
86
87
88
89
90
91

            xAxis.scale(xScaleNew);
            xAxisDraw.call(xAxis);

            svg.selectAll(".label")
                .attr("x", value => xScaleNew(value.periodSpan?.[0]))
92
                .attr("y", value => yScaleNew(value.periodId));
amarcic's avatar
amarcic committed
93
94
        };
        const zimzoom = zoom()
amarcic's avatar
amarcic committed
95
            .scaleExtent([1,5])
96
            .translateExtent([[0,0], [width, height+margin.bottom+margin.top]])
amarcic's avatar
amarcic committed
97
98
99
100
101
102
            .on("zoom", handleZoom);
        const initZoom = () => {
            svg
                .call(zimzoom);
        }

103
        //add bars (without extension) for each period on enter and return a selection of all entering and updating nodes
amarcic's avatar
amarcic committed
104
        const selectionEnteringAndUpdating = selection.join(
amarcic's avatar
amarcic committed
105
106
            enter => enter
                .append("rect")
amarcic's avatar
amarcic committed
107
108
                    .attr("class", "bar")
                    .attr("fill", "#69b3a2")
amarcic's avatar
amarcic committed
109
110
        );

amarcic's avatar
amarcic committed
111
        console.log("new and updating: ", selectionEnteringAndUpdating);
amarcic's avatar
amarcic committed
112

113
        //position and extend bars according to temporal extent of period
amarcic's avatar
amarcic committed
114
        selectionEnteringAndUpdating
115
            .attr("height", yScale.bandwidth())
116
117
118
            .transition()
            .attr("x", value => xScale(value.periodSpan?.[0]))
            .attr("y", (value, index) => yScale(periodIds[index]))
amarcic's avatar
amarcic committed
119
120
            .attr("width", value => Math.abs(xScale(value.periodSpan?.[0])-xScale(value.periodSpan?.[1]))||0)

121
122
        //add labels to the bars
        selectionLabels
amarcic's avatar
amarcic committed
123
124
125
126
127
128
            .enter()
            .append("text")
                .attr("class", "label")
                .attr("x", value => xScale(value.periodSpan?.[0]))
                .attr("y", value => yScale(value.periodId))
                .text(value => value.periodName);
129

130
131
132
133
        selectionLabels
            .attr("x", value => xScale(value.periodSpan?.[0]))
            .attr("y", value => yScale(value.periodId))

134
        //remove labels on exit
135
136
137
138
        selectionLabels
            .exit()
            .remove()

amarcic's avatar
amarcic committed
139
        initZoom();
amarcic's avatar
amarcic committed
140
141
    }

142
143
144
145
    const updateTimeline = () => {

    }

amarcic's avatar
amarcic committed
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
295
296
    /*
    useEffect(() => {



        svg.attr()


        //remove previously rendered timeline bars in the case there is no data from the current search
        //if (!timelineObjectsData||!byPeriodData||byPeriodData.size===0) {
        if (!data||data.size===0) {
            svg.select(".bars")
                .selectAll(".bar").remove()
            svg.select(".bars")
                .selectAll(".label").remove()
            svg.select(".background").selectAll("rect").remove();
        } else {
            const periodIds = [...data.keys()];

            //scale for the x axis
            const xScale = scaleLinear()
                .domain(xDomain)
                .range([0,width])

            //scale for the y axis
            const yScale = scaleBand()
                .domain(periodIds)
                .range([height,0])
                .padding(0.2)

            //todo: replace this temporary cleanup of the background svg group
            svg.select(".background").selectAll("rect").remove();



            //select and position svg element for the timeline
            const timelineCanvas = svg.select(".bars")
                .attr("transform",`translate(${margin.left}, ${margin.top})`)

            //bind svg groups for bars and labels to the values of the data (map grouped by periods)
            const barGroups = timelineCanvas
                .selectAll(".barGroup")
                .data([...data.values()], (data,index) => data.periodName+data.periodSpan[0]);
            //todo: evaluate if generating the key form period name + period beginning sufficiently unique?
            //console.log("bar groups: ", barGroups);

            //instructions for joining the synced data and group elements: add svg g, rect and text elements on enter
            //returns a selection of new and updating groups
            const newAndUpdatedGroups = barGroups
                .join(
                    enter => {
                        let group = enter
                            .append("g");
                        group.attr("class","barGroup");
                        group
                            .append("rect")
                            .attr("class", "bar")
                            .attr("height", yScale.bandwidth())
                            .attr("fill", "#69b3a2");
                        group
                            .append("text")
                            .attr("class","label");
                        return group;
                    }
                )

            //position all new and updating groups
            newAndUpdatedGroups
                .attr("transform", (value, index) => `translate(${xScale(value.periodSpan?.[0])},${yScale(periodIds[index])})`)

            //extend the svg rect elements as chart bars according to the data and return as "bar"
            const bar = newAndUpdatedGroups.selectAll(".bar")
                .transition()
                .attr("width", value => Math.abs(xScale(value.periodSpan?.[0])-xScale(value.periodSpan?.[1]))||0);

            //add period names as text labels to the groups and return as "labels"
            const labels = newAndUpdatedGroups.selectAll(".label")
                .text(value => value.periodName);
            console.log("new and updated after labels: ", newAndUpdatedGroups);

            //attach click event and sort function to sort button;
            select(".sortButton").on("click", () =>
                svg.selectAll(".barGroup").sort( (a,b) => ascending(parseInt(a.periodSpan?.[0]),parseInt(b.periodSpan?.[0])) )
                    .attr("transform", (value, index) => `translate(${xScale(value.periodSpan?.[0])},${yScale(periodIds[index])})`)
            );

            //on click show detailed view of dated objects for a period
            newAndUpdatedGroups.on("click", (event, value) => {

                    //const element = svg.selectAll(".bar").nodes(),
                     //   index = element.indexOf(event.currentTarget);

                    const itemDatingMin = min(value.items, item => item.spanDated?.[0]),
                        itemDatingMax = max(value.items, item => item.spanDated?.[1]);

                    const xScaleDetail = scaleLinear()
                        .domain([itemDatingMin,itemDatingMax])
                        .range([0,width])

                    const yScaleDetail = scaleLinear()
                        .domain([0, value.items.length])
                        .range([height,0]);

                    //remove bars and labels
                    svg.selectAll(".bar").remove();
                    svg.selectAll(".label").remove();

                    svg.select(".background").selectAll("rect").remove();

                    //attach x axis
                    svg.select(".xAxis")
                        .attr("transform", `translate(0,${height})`)
                        .call(axisBottom(xScaleDetail))

                    //join svg rect elements with array of item dating
                    svg.select(".bars")
                        .selectAll("rect").data(value.items).join(
                            enter => enter.append("rect")
                        ).attr("class","bar")
                        .attr("x", value => xScaleDetail(value.spanDated?.[0]))
                        .attr("y", (value,index) => yScaleDetail(index))
                        .attr("height", 5)
                        .transition()
                        .attr("width", value => Math.abs(xScaleDetail(value.spanDated?.[0])-xScaleDetail(value.spanDated?.[1]))+1||0)

                    //paint on the background a rect representing the temporal extension of the period
                    svg.select(".background")
                        .selectAll("rect").data([value]).join("rect")
                        .attr("width", Math.abs(xScaleDetail(value.periodSpan?.[0])-xScaleDetail(value.periodSpan?.[1]))||0)
                        .attr("height", height)
                        .attr("x", xScaleDetail(value.periodSpan[0]))
                        .transition()
                        .attr("opacity", 0.3)
                })

        }
    }, [data])
    */

    return (
        <div className="timeline">
            <svg ref={svgRef}>
                <g className="timelineGroup">
                    <g className="xAxis"></g>
                    <g className="yAxis"></g>
                </g>
                <g className="background" />
            </svg>
        </div>
    )
};