TimelineChart.jsx 15 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";
4
import { select, scaleBand, axisBottom, scaleLinear, scaleQuantize, zoom, extent } 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
    const svgRef = useRef();

14
    console.log("dimensions", props.dimensions)
15
16
    //todo: make highlighted global state?
    let highlighted = {
amarcic's avatar
amarcic committed
17
        objects: ["1080824", "1086070"],
18
19
20
        periods: [],
        locations: []
    };
21
    const xDomain = getTimeRangeOfTimelineData(props.filteredTimelineData,"period");
22
23
    const dataUnsorted = newGroupByPeriods(props.filteredTimelineData);
    const data = dataUnsorted && new Map([...dataUnsorted.entries()]
24
        //sort by period start year
25
        .sort( (a,b) =>
26
            a[1].periodSpan?.[0] - b[1].periodSpan?.[0] ));
27
28

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

30
    //console.log("filteredTimelineData: ", props.filteredTimelineData);
31
    console.log("grouped by periods and sorted: ", data)
32
    //console.log("sorted data: ", dataUnsorted)
amarcic's avatar
amarcic committed
33
34
35

    //setting up the svg after first render
    useEffect(() => {
36
        const { width, height, margin } = props.dimensions;
37
        //console.log("width", width)
amarcic's avatar
amarcic committed
38
39
40
41
42
43
        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})`);

44
    }, [props.dimensions]);
amarcic's avatar
amarcic committed
45

46
    //draw timeline everytime filteredTimelineData changes
amarcic's avatar
amarcic committed
47
    useEffect( () => {
48
49
        drawTimeline(timelineData, props.dimensions)
    }, [props.filteredTimelineData, props.dimensions] );
amarcic's avatar
amarcic committed
50

51
//todo: check if still depending on outer scope (like height, width, margin)
52
    const drawTimeline = (timelineConfig, dimensions) => {
53
54

        const { data, svgRef, xDomain } = timelineConfig;
55
        const { width, height, margin } = dimensions;
56
        const svg = select(svgRef.current);
57
        const labelRenderLimit = 8;
58

59
        //empty canvas in case no data is found by query
60
61
62
63
64
        if(!data||data.size===0) {
            svg.selectAll(".bar").remove();
            svg.selectAll(".label").remove();
            return;
        }
amarcic's avatar
amarcic committed
65
66
        //console.log([...data.values()]);

67

amarcic's avatar
amarcic committed
68
        const selection = svg.select(".timelineGroup").selectAll("rect").data([...data.values()], data => data.periodId);
69
        const selectionLabels = svg.select(".timelineGroup").selectAll(".label").data([...data.values()], data => data.periodId);
amarcic's avatar
amarcic committed
70
        const periodIds = [...data.keys()];
71
        const itemQuantityExtent = extent([...data.values()].map( value => value.items.length));
72

amarcic's avatar
amarcic committed
73
74
75
76
77
78
79
80
81
82
        //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)

83
84
85
        //add x axis to svg
        const xAxis = axisBottom(xScale);
        const xAxisDraw = svg.select(".xAxis")
86
            .attr("transform", `translate(0,${height+margin.top})`)
87
88
            .call(xAxis);

89
        //todo: application wide color scale should be used; colors are not that great
90
91
        const colorScale = scaleQuantize()
            .domain(itemQuantityExtent)
92
            .range(["#5AE6BA","#4BC8A3","#3EAA8C","#318D75","#25725F"]);
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
        //function to add labels to the bars (when bandwith is heigh enough for readable labels)
        //todo: remove outer dependency on selectionLabels
        const addLabels = (bandwidth, renderLimit) => {
            if (bandwidth > renderLimit) {
                selectionLabels
                    .enter()
                    .append("text")
                    .attr("class", "label")
                    .attr("x", value => xScale(value.periodSpan?.[0]))
                    .attr("y", value => yScale(value.periodId))
                    .text(value => value.periodName);

                //position labels
                selectionLabels
                    .attr("x", value => xScale(value.periodSpan?.[0]))
                    .attr("y", value => yScale(value.periodId))

                //remove labels on exit
                selectionLabels
                    .exit()
                    .remove()
            } else {
                svg.selectAll(".label")
                    .remove();
            }
        }

121
        //add clip path to svg for later use
122
123
124
125
126
127
128
129
130
131
        if (document.getElementById("clip")===null&&height&&width) {
            svg.append("defs").append("clipPath")
                .attr("id","clip")
                .append("rect")
                .attr("width", width)
                .attr("height", height)
                .attr("x", 0)
                .attr("y", 0);
        }

132
        //apply the prepared clip path to the svg group containing the bars and labels
133
134
135
        svg.select(".timelineGroup")
            .attr("clip-path", "url(#clip)");

amarcic's avatar
amarcic committed
136
137
        //set up zoom and pan
        const handleZoom = (event) => {
138
139
140
141
142
143
144

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

            const xScaleNew = transform.rescaleX(xScale);
145
            const yScaleNew = yScale.range([height,0].map( d => transform.applyY(d) ));
146
147
148
149

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

150
151
            addLabels(yScaleNew.bandwidth(), labelRenderLimit);

152
153
            svg.selectAll(".label")
                .attr("x", value => xScaleNew(value.periodSpan?.[0]))
154
                .attr("y", value => yScaleNew(value.periodId));
amarcic's avatar
amarcic committed
155
156
        };
        const zimzoom = zoom()
amarcic's avatar
amarcic committed
157
            .scaleExtent([1,5])
158
            .translateExtent([[0,0], [width, height+margin.bottom+margin.top]])
amarcic's avatar
amarcic committed
159
160
161
162
163
164
            .on("zoom", handleZoom);
        const initZoom = () => {
            svg
                .call(zimzoom);
        }

165
        //add bars (without extension) for each period on enter and return a selection of all entering and updating nodes
amarcic's avatar
amarcic committed
166
        const selectionEnteringAndUpdating = selection.join(
amarcic's avatar
amarcic committed
167
168
            enter => enter
                .append("rect")
amarcic's avatar
amarcic committed
169
                    .attr("class", "bar")
170
                    //.attr("fill", "#69b3a2")
amarcic's avatar
amarcic committed
171
172
        );

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

175
        //position and extend bars according to temporal extent of period
amarcic's avatar
amarcic committed
176
        selectionEnteringAndUpdating
177
            .attr("height", yScale.bandwidth())
178
179
180
            .transition()
            .attr("x", value => xScale(value.periodSpan?.[0]))
            .attr("y", (value, index) => yScale(periodIds[index]))
amarcic's avatar
amarcic committed
181
            .attr("width", value => Math.abs(xScale(value.periodSpan?.[0])-xScale(value.periodSpan?.[1]))||0)
182
            .attr("fill", value => colorScale(value.items.length))
amarcic's avatar
amarcic committed
183
184
185
186
            .attr("stroke", value => highlighted.objects.some( id =>
                value.items.map( item => item.id).indexOf(id) > -1)
                ? "black"
                : "red")
amarcic's avatar
amarcic committed
187

188
        //display tooltip when mouse enters bar on chart
189
190
        selectionEnteringAndUpdating
            .on("mouseenter", (event, value) => {
amarcic's avatar
amarcic committed
191
192
193
194
195
196
                select(event.currentTarget)
                    .attr("id", "mouse-target")
                    .on("mouseleave", () => {
                        select("#mouse-target")
                            .attr("id", null)
                    })
197
198
                highlighted.objects = value.items.map( item => item.id);
                //console.log("high: ", highlighted)
amarcic's avatar
amarcic committed
199

200
201
202
203
204
                svg
                    .selectAll(".tooltip")
                    .data([value])
                    .join("text")
                    .attr("class", "tooltip")
205
                    .text( value => yScale.bandwidth() <= labelRenderLimit
206
207
                        ? `${value.periodName}: ${value.items.length} ${t("Item", {count: value.items.length})}`
                        : `${value.items.length} ${t("Item", {count: value.items.length})}`)
208
209
                    .attr("text-anchor", "middle")
                    .attr("x", value => xScale(value.periodSpan?.[0]))
210
                    .attr("y", value => yScale(value.periodId)+yScale.bandwidth()/*+margin.top*/)
211
212
            });

213
214
215
216
217
218
219
220
        //remove tooltips when mouse leaves the svg
        svg
            .on("mouseleave", () => {
            svg
                .selectAll(".tooltip")
                .remove()
        } )

221
        addLabels(yScale.bandwidth(), labelRenderLimit);
222

223
        //apply zoom
amarcic's avatar
amarcic committed
224
        initZoom();
amarcic's avatar
amarcic committed
225
226
    }

227
228
229
230
    const updateTimeline = () => {

    }

amarcic's avatar
amarcic committed
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
    /*
    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">
374

amarcic's avatar
amarcic committed
375
                </g>
376
377
                <g className="xAxis"></g>
                <g className="yAxis"></g>
amarcic's avatar
amarcic committed
378
379
380
381
382
                <g className="background" />
            </svg>
        </div>
    )
};