Skip to content

Commit

Permalink
1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
AkimaLunar committed Mar 3, 2020
0 parents commit fe88c2c
Show file tree
Hide file tree
Showing 34 changed files with 2,623 additions and 0 deletions.
18 changes: 18 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.

# dependencies
/node_modules

# testing
/coverage

# production
/build

# misc
.DS_Store
.env
npm-debug.log*
yarn-debug.log*
yarn-error.log*

8 changes: 8 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"arrowParens": "always",
"printWidth": 80,
"semi": true,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "es5"
}
1,623 changes: 1,623 additions & 0 deletions README.md

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "example-d3-one",
"version": "0.1.0",
"private": true,
"dependencies": {
"d3": "^5.15.0",
"prop-types": "^15.7.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "0.9.x",
"uuid": "^7.0.1"
},
"devDependencies": {},
"scripts": {
"build": "react-scripts build",
"eject": "react-scripts eject",
"generate": "plop",
"start": "react-scripts start",
"test": "react-scripts test --env=jsdom"
}
}
7 changes: 7 additions & 0 deletions plopfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const componentGenerator = require('./templates/component');
const d3ChartGenerator = require('./templates/d3-chart');

module.exports = function(plop) {
plop.setGenerator('component', componentGenerator);
plop.setGenerator('d3', d3ChartGenerator);
};
Binary file added public/favicon.ico
Binary file not shown.
31 changes: 31 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
18 changes: 18 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React from 'react';

import Competition from './components/Competition';
import Inventory from './components/Inventory';
import Page from './components/Page';

const App = () => (
<div className="App">
<Page className="centered" alt>
<Inventory />
</Page>
<Page>
<Competition />
</Page>
</div>
);

export default App;
61 changes: 61 additions & 0 deletions src/components/Chart/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import validate from './validate';
import useDebounce from '../../utils/hooks/useDebounce';

const Chart = ({ className, data, d3: D3 }) => {
if (!D3 || !validate(D3)) {
return <div />;
}

const debouncedData = useDebounce(data, 150);

const chartRef = useRef(null);
const chartClass = useRef(null);

// Initialize chart svg container ==========================================
useEffect(() => {
if (!chartRef.current) {
return false;
}
chartClass.current = new D3(chartRef.current);

return () => {
chartClass.current.destroy();
};
}, []);

// Update chart on changes in data =========================================
useEffect(() => {
debouncedData &&
chartClass.current &&
chartClass.current.setData(debouncedData);

chartClass.current && chartClass.current.render();
}, [debouncedData]);

// Resize chart on window.resize ===========================================
const isClient = typeof window === 'object';
useEffect(() => {
if (!isClient) {
return false;
}
const handleResize = () =>
chartClass.current.resize &&
chartClass.current.resize(chartRef.current);
window.addEventListener('resize', handleResize);

return () => window.removeEventListener('resize', handleResize);
}, []);

// Render ==================================================================
return <div className={className} ref={chartRef}></div>;
};

Chart.propTypes = {
className: PropTypes.string,
data: PropTypes.any,
d3: PropTypes.func.isRequired,
};

export default Chart;
32 changes: 32 additions & 0 deletions src/components/Chart/validate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export default function(chart) {
const _c = new chart();
const errors = [];
!_c.setData &&
errors.push({
method: 'setData',
info: 'Required to set data on a chart.',
});
!_c.render &&
errors.push({
method: 'render',
info:
'Required for to render the chard with the data and to update the chart when data changes.',
});
!_c.destroy &&
errors.push({
method: 'destroy',
info: 'Required for cleanup when component unmounts.',
});
!_c.canvas &&
errors.push({
method: 'canvas',
info: 'Required svg canvas to render the chart on.',
});

if (errors.length > 0) {
console.error(`Methods and/or properties missing on the chart:`, chart);
console.table(errors);
return false;
}
return true;
}
138 changes: 138 additions & 0 deletions src/components/Competition/d3/scatter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import * as d3 from 'd3';

const HEIGHT = 300;

export default class Chart {
constructor(element) {
this.element = element;
this.data = null;
this.margin = {
top: 40,
right: 60,
bottom: 40,
left: 60,
};
this.size = element ? element.getBoundingClientRect() : {};
this.init();
}

get height() {
return HEIGHT - this.margin.top - this.margin.bottom;
}

get width() {
return this.size.width - this.margin.left - this.margin.right;
}

init = () => {
this.svg = d3
.select(this.element)
.append('svg')
.attr('height', this.height + this.margin.top + this.margin.bottom)
.attr('width', this.width + this.margin.left + this.margin.right);

this.canvas = this.svg
.append('g')
.attr(
'transform',
`translate(${this.margin.left}, ${this.margin.top})`
);

this.xAxis = this.canvas
.append('g')
.attr('transform', `translate(0, ${this.height})`);
this.yAxis = this.canvas.append('g');
};

setData = (data) => {
this.data = data;
};

resize = (element) => {
this.destroy();
this.size = element.getBoundingClientRect();
this.init();
this.render();
};

render = () => {
if (!this.data) {
return;
}

// Set scales ==========================================================
const xScale = d3
.scaleLinear()
.domain([0, d3.max(this.data, (d) => d.time)])
.range([0, this.width]);

const yScale = d3
.scaleLinear()
.domain([0, d3.max(this.data, (d) => d.points)])
.range([this.height, 0]);

// Set axis ============================================================
this.xAxis
.transition()
.duration(500)
.ease(d3.easePoly)
.call(d3.axisBottom(xScale));

this.yAxis
.transition()
.duration(500)
.ease(d3.easePoly)
.call(d3.axisLeft(yScale));

// Data enters the chart ===============================================
const enter = (enter) =>
enter
.append('circle')
.attr('cx', (d) => xScale(d.time))
.attr('cy', (d) => yScale(d.points))
.attr('r', 0)
.attr('fill', '#FE2E3B')
.call((enter) =>
enter
.transition()
.duration(250)
.ease(d3.easePoly)
.attr('r', 15)
.transition()
.duration(250)
.ease(d3.easePoly)
.attr('r', 5)
.attr('fill', '#E07B9B')
);

// Data updates ========================================================
const update = (update) =>
update
.transition()
.duration(500)
.ease(d3.easePoly)
.attr('cx', (d) => xScale(d.time))
.attr('cy', (d) => yScale(d.points))
.attr('r', 5)
.attr('fill', '#E07B9B');

// Data leaves the chart ===============================================
const exit = (exit) =>
exit
.transition()
.duration(500)
.ease(d3.easePoly)
.attr('r', 0)
.remove();

// General update pattern ==============================================
this.canvas
.selectAll('circle')
.data(this.data)
.join(enter, update, exit);
};

destroy = () => {
this.svg.remove();
};
}
31 changes: 31 additions & 0 deletions src/components/Competition/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import React, { useState, useCallback } from 'react';
import randomNumber from '../../utils/helpers/randomNumber';
import './styles.css';

import BarChart from './d3/scatter';
import Chart from '../Chart';
import Form from './partials/form';
import Table from './partials/table';

const DATA = Array.from(Array(3)).map(() => ({
time: randomNumber(30, 120),
points: randomNumber(0, 20),
}));

const Competition = () => {
const [data, setData] = useState(DATA);

const reset = useCallback(() => setData([]), []);
const add = useCallback((item) => setData([...data, item]), [data]);

return (
<div className="competition">
<h1 className="competition__title">Competition</h1>
<Chart data={data} d3={BarChart} />
<Form onSubmit={add} onReset={reset}></Form>
<Table data={data}></Table>
</div>
);
};

export default Competition;
Loading

0 comments on commit fe88c2c

Please sign in to comment.