21 | This page shows an implementation of the canonical dc.js example, in React. We love dc.js and we love React,
22 | but it sometimes felt they did not love each other. The implementation demonstrated here uses React hooks to
23 | get everyone to play along
24 |
25 |
26 | Who Made This ?
27 |
28 |
29 | LightTag! LightTag makes tools to label NLP data with teams.
30 |
56 | )
57 | }
58 |
--------------------------------------------------------------------------------
/src/dc/moveChart.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import * as dc from "dc";
3 | import { scaleTime, timeMonth, timeMonths } from "d3";
4 | import { ChartTemplate } from "./chartTemplate";
5 | import { dateFormat, numberFormat } from "./cxContext";
6 | const reducerAdd = (p, v) => {
7 | ++p.days;
8 | p.total += (v.open + v.close) / 2;
9 | p.avg = Math.round(p.total / p.days);
10 | return p;
11 | };
12 |
13 | const reducerRemove = (p, v) => {
14 | --p.days;
15 | p.total -= (v.open + v.close) / 2;
16 | p.avg = p.days ? Math.round(p.total / p.days) : 0;
17 | return p;
18 | };
19 |
20 | const reducerInitial = () => ({ days: 0, total: 0, avg: 0 });
21 | const moveChartFunc = (divRef, ndx) => {
22 | const dimension = ndx.dimension(d => d.month);
23 |
24 | const moveChart = dc.lineChart(divRef);
25 | const monthlyMoveGroup = dimension
26 | .group()
27 | .reduceSum(d => Math.abs(d.close - d.open));
28 | const indexAvgByMonthGroup = dimension
29 | .group()
30 | .reduce(reducerAdd, reducerRemove, reducerInitial);
31 |
32 | moveChart
33 | .dimension(dimension)
34 | .mouseZoomable(true)
35 | .transitionDuration(1000)
36 | .x(scaleTime().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)]))
37 | .round(timeMonth.round)
38 | .xUnits(timeMonths)
39 | .elasticY(true)
40 | .renderHorizontalGridLines(true)
41 | .legend(
42 | dc
43 | .legend()
44 | .x(800)
45 | .y(10)
46 | .itemHeight(13)
47 | .gap(5)
48 | )
49 | .brushOn(false)
50 | .group(indexAvgByMonthGroup, "Monthly Index Average")
51 | .valueAccessor(function(d) {
52 | return d.value.avg;
53 | })
54 | .stack(monthlyMoveGroup, "Monthly Index Move", function(d) {
55 | return d.value;
56 | })
57 | .title(function(d) {
58 | var value = d.value.avg ? d.value.avg : d.value;
59 | if (isNaN(value)) {
60 | value = 0;
61 | }
62 | return dateFormat(d.key) + "\n" + numberFormat(value);
63 | });
64 |
65 | return moveChart;
66 | };
67 |
68 | export const MoveChart = props => (
69 |
70 | )
71 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/dc/bubbleChart.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import * as dc from "dc";
3 | import { timeYear, schemeRdYlGn, scaleLinear } from "d3";
4 | import { numberFormat } from "./cxContext";
5 | import { ChartTemplate } from "./chartTemplate";
6 |
7 | const groupAddReducer =(p,v)=>{
8 | ++p.count;
9 | p.absGain += v.close - v.open;
10 | p.fluctuation += Math.abs(v.close - v.open);
11 | p.sumIndex += (v.open + v.close) / 2;
12 | p.avgIndex = p.sumIndex / p.count;
13 | p.percentageGain = p.avgIndex ? (p.absGain / p.avgIndex) * 100 : 0;
14 | p.fluctuationPercentage = p.avgIndex
15 | ? (p.fluctuation / p.avgIndex) * 100
16 | : 0;
17 | return p;
18 | }
19 | const groupRemoveRudcer =(p, v) =>{
20 | --p.count;
21 | p.absGain -= v.close - v.open;
22 | p.fluctuation -= Math.abs(v.close - v.open);
23 | p.sumIndex -= (v.open + v.close) / 2;
24 | p.avgIndex = p.count ? p.sumIndex / p.count : 0;
25 | p.percentageGain = p.avgIndex ? (p.absGain / p.avgIndex) * 100 : 0;
26 | p.fluctuationPercentage = p.avgIndex ? (p.fluctuation / p.avgIndex) * 100 : 0;
27 | return p;
28 | }
29 |
30 | const groupInitalizer = ()=> {
31 | return {
32 | count: 0,
33 | absGain: 0,
34 | fluctuation: 0,
35 | fluctuationPercentage: 0,
36 | sumIndex: 0,
37 | avgIndex: 0,
38 | percentageGain: 0
39 | };
40 | }
41 |
42 | const bubbleChartFunc = (divRef, ndx) => {
43 | const yearlyDimension = ndx.dimension(d => timeYear(d.dd).getFullYear());
44 | const yearlyPerformanceGroup = yearlyDimension.group()
45 | .reduce(groupAddReducer,groupRemoveRudcer,groupInitalizer);
46 | const yearlyBubbleChart = dc.bubbleChart(divRef); // Divref is a refere3nce to the div we're attaching to
47 | yearlyBubbleChart
48 | .transitionDuration(1500)
49 | .dimension(yearlyDimension)
50 | .group(yearlyPerformanceGroup)
51 | .colors(schemeRdYlGn[9]) // why the 9 ?
52 | .colorAccessor(d => d.value.absGain)
53 | .keyAccessor(p => p.value.absGain)
54 | .valueAccessor(p=>p.value.percentageGain)
55 | .radiusValueAccessor(p => p.value.fluctuationPercentage)
56 | .maxBubbleRelativeSize(0.3)
57 | .x(scaleLinear().domain([-2500, 2500]))
58 | .y(scaleLinear().domain([-100, 100]))
59 | .r(scaleLinear().domain([0, 4000]))
60 | .elasticY(false)
61 | .elasticX(true)
62 | .yAxisPadding(100)
63 | .xAxisPadding('10%')
64 | .renderHorizontalGridLines(true)
65 | .renderVerticalGridLines(true)
66 | .xAxisLabel('Index Gain')
67 | .yAxisLabel('Index Gain %')
68 | .renderLabel(true)
69 | .label(p=>p.key)
70 | .renderTitle(true)
71 | .title( (p)=>(
72 | [
73 | p.key,
74 | 'Index Gain: ' + numberFormat(p.value.absGain),
75 | 'Index Gain in Percentage: ' + numberFormat(p.value.percentageGain) + '%',
76 | 'Fluctuation / Index Ratio: ' + numberFormat(p.value.fluctuationPercentage) + '%'
77 | ].join('\n')
78 | ))
79 | .yAxis().tickFormat(v=>`${v}%`)
80 | return yearlyBubbleChart
81 |
82 | };
83 | export const BubbleChart = props => (
84 |
85 | )
86 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React + DC.JS
2 |
3 | This is a POC of using [DC.JS within a React application](https://www.lighttag.io/blog/react-dc-js/).
4 |
5 | [demo](https://lighttag.github.io/dcjs-in-react/), [blog post](https://www.lighttag.io/blog/react-dc-js/)
6 |
7 | ## The Problem
8 |
9 | React is, well React, and DC.JS is a library for making interactive charts and dashboards on high dimensional data. [We](https://www.lighttag.io) want to use DC.JS inside of our react app but they don't play nice.
10 |
11 | DC is powered by D3, which manipulates the DOM. Since React also manipulates the dom this has potential for conflicts and significant cognitive overhead.
12 |
13 | DC is also powered by crossfilter, which manages the state of your data and filters. Generally, we let React manage data/state either directly in state or through something like redux. This also has potential for conflicts and overhead.
14 |
15 | ## The Solution
16 |
17 | ### Keep Crossfilter in a Context Provider
18 |
19 | DC works by keeping a "global" crossfilter object witht he data, and letting the charts apply various filters on it. We tried to put that crossfilter inside of a context object, and render all charts using it.
20 |
21 | You can see the code [here](/src/dc/cxContext.js) but the crux of it is
22 |
23 | ```es6
24 | export class DataContext extends React.Component {
25 | constructor(props) {
26 | super(props);
27 | this.state={loading:false,hasNDX:false};
28 | }
29 |
30 | componentDidMount(){
31 | if (this.state.hasNDX){
32 | return
33 | }
34 | if(this.state.loading){
35 | return
36 | }
37 | this.setState({loading:true})
38 | {/*do things here to get data */}
39 | this.ndx = crossfilter(data); //TODO possibly need to update this
40 | this.setState({loading:false,hasNDX:true})
41 | })
42 | }
43 |
44 | render() {
45 | if(!this.state.hasNDX){
46 |
47 | return null;
48 | }
49 | return (
50 |
51 |
52 | {this.props.children}
53 |
54 |
55 | );
56 | }
57 | }
58 |
59 | ```
60 |
61 | ### Create A "Chart Wrapper Component"
62 |
63 | DC uses a declarative syntax to define charts. You give it a DOM element and data from crossfilter, and it gives you a chart back. If you use the same crossfilter object the charts will interact, which is what we want.
64 |
65 | To get this working in react we can break it down into two parts. 1) Is a react component that creates an element and has access to the crossfilter context. 2) Is a function that receives the element and crossfilter object and creates a chart.
66 |
67 | Since part 1 repeats, it makes sense to abstract it into it's own component, which you can find [here](/src/chartTemplate.js)
68 |
69 | A simplified version of it looks like this
70 |
71 | ```es6
72 | export const ChartTemplate = props => {
73 | /*
74 | We render the dc chart using an effect. We want to pass the chart as a prop after the dc call,
75 | but there is nothing by default to trigger a re-render and the prop, by default would be undefined.
76 | To solve this, we 1) hold the chart in state using a hook 2) make sure the effect hook is run exactly once
77 | */
78 | const context = React.useContext(CXContext);
79 | const [chart,updateChart] = React.useState(null);
80 | const ndx = context.ndx;
81 | const div = React.useRef(null);
82 | React.useEffect(() => {
83 | const newChart = props.chartFunction(div.current, ndx); // chartfunction takes the ref and does something with it
84 |
85 | newChart.render();
86 | updateChart(newChart);
87 | },1); {/*Run this exactly once */}
88 | return (
89 |
94 |
95 | );
96 | };
97 |
98 | ```
99 |
100 | ## Making A Chart
101 |
102 | From there, making a new chart is just writing standard dc.js code as a function, and passing that function as a
103 | prop to the template component. Victory!
104 |
105 | ## Brought To You By LightTag
106 | LightTag is a tool for [NLP annotation](https://www.lighttag.io).
107 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------