Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Olek first commit #45

Merged
merged 1 commit into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 35 additions & 71 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"babel-plugin-react-css-modules": "^5.2.6",
"file-loader": "^6.2.0",
"html2canvas": "^1.4.1",
"ionicons": "^7.3.0",
"jspdf": "^2.5.1",
Expand Down
Binary file added src/assets/dial_bg.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
131 changes: 131 additions & 0 deletions src/components/Results/EnergyScore/arc.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import React, { useState, useEffect, useRef } from 'react';

const Arc = ({ score, width, height }) => {
const maxScore = 100;
const scorePerArc = maxScore / 3;
const arcPathsRef = useRef([]);
const [circleInfo, setCircleInfo] = useState({ x: 0, y: 0, color: '#fff' });
const [center, setCenter] = useState({ x: 0, y: 0 });
const [circleRadius, setCircleRadius] = useState(0);

const gradientColors = {
gradient1: "#F27374",
gradient2: "#FFA685",
gradient3: "#4892A7"
};

const arcsInfo = [
{ startAngle: 230, endAngle: 310, gradientId: "gradient1" },
{ startAngle: 320, endAngle: 400, gradientId: "gradient2" },
{ startAngle: 50, endAngle: 130, gradientId: "gradient3" }
];

const scoreToAngle = (arcScore, arcIndex) => {
const arcLength = arcsInfo[arcIndex].endAngle - arcsInfo[arcIndex].startAngle;
return arcsInfo[arcIndex].startAngle + (arcScore / scorePerArc) * arcLength;
};

const describeArc = (radius, startAngle, endAngle) => {
const start = polarToCartesian(center.x, center.y, radius, startAngle);
const end = polarToCartesian(center.x, center.y, radius, endAngle);
const largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1';

return [
'M', start.x, start.y,
'A', radius, radius, 0, largeArcFlag, 1, end.x, end.y
].join(' ');
};

const calculateScores = (totalScore) => {
let remainingScore = totalScore;
return arcsInfo.map((_, index) => {
if (remainingScore > scorePerArc) {
remainingScore -= scorePerArc;
return scorePerArc;
} else {
const scoreForArc = remainingScore;
remainingScore = 0;
return scoreForArc;
}
});
};

useEffect(() => {
setCenter({ x: width / 2, y: height / 2 });
setCircleRadius(0.95 * Math.min(width, height) / 2 - 1);
}, [score, width, height]);

useEffect(() => {
const scores = calculateScores(score);
const scoresToArr = scores.filter(score => score > 0);
scoresToArr.forEach((score, index) => {
const pathElement = arcPathsRef.current[index];
if (pathElement && score > 0) {
const endAngle = scoreToAngle(score, index);
const arcPath = describeArc(circleRadius, arcsInfo[index].startAngle, endAngle);
pathElement.setAttribute('d', arcPath);

if (index === scoresToArr.length - 1) {
const { x, y } = polarToCartesian(center.x, center.y, circleRadius, endAngle);
setCircleInfo({ x: x - 12, y: y - 12, color: gradientColors[arcsInfo[index].gradientId] });
}
}
});
}, [center, circleRadius, score]);

return (
<div style={{ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0 }}>
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
<svg width="100%" height="100%">
<defs>
<linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stopColor="#FE8E60" />
<stop offset="100%" stopColor="#F27374" />
</linearGradient>
<linearGradient id="gradient2" x1="100%" y1="0%" x2="0%" y2="0%">
<stop offset="0%" stopColor="#E1BE45" />
<stop offset="52%" stopColor="#FF8B60" />
<stop offset="100%" stopColor="#FFA685" />
</linearGradient>
<linearGradient id="gradient3" x1="100%" y1="100%" x2="100%" y2="100%">
<stop offset="0%" stopColor="#E8B34C" />
<stop offset="86%" stopColor="#4892A7" />
</linearGradient>
</defs>
{arcsInfo.map((arc, index) => (
<path
key={index}
ref={el => (arcPathsRef.current[index] = el)}
fill="none"
stroke={`url(#${arc.gradientId})`}
strokeWidth="8"
strokeLinecap="round"
/>
))}
</svg>
<div style={{ position: 'absolute', left: circleInfo.x, top: circleInfo.y }}>
<svg>
<circle
cx={12}
cy={12}
r="7"
fill="white"
stroke={circleInfo.color}
strokeWidth="5"
/>
</svg>
</div>
</div>
</div>
)
}

const polarToCartesian = (centerX, centerY, radius, angleInDegrees) => {
const angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0;
return {
x: centerX + radius * Math.cos(angleInRadians),
y: centerY + radius * Math.sin(angleInRadians),
};
};

export default Arc;
8 changes: 4 additions & 4 deletions src/components/Results/EnergyScore/energyscore.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,18 @@ const EnergyScore = (props) => {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
backgroundColor: '#f5f5f5',
backgroundColor: '#f2f0f1',
borderRadius: '100px',
padding: '10px 20px',
height: '200px',
margin: '20px'
}}
>
<div style={{ width: '75%', height: '100%', marginRight: '20px' }}>
<div style={{ width: '100%', height: '100%', marginRight: '20px' }}>
<ScoreRing value={score} scoreLabel={'Good'} />
</div>
<div style={{ width: '60%' }}>
<h2>Score is based on the estimated CO2 emissions of your home</h2>
<h5>Score is based on the estimated CO2 emissions of your home</h5>
</div>
</div>
<Grid container justifyContent="space-between">
Expand All @@ -43,7 +43,7 @@ const EnergyScore = (props) => {
score={score}
details={props.details}
/>
<CompareButton
<CompareButton
yourHomeValue={props.yourHomeValue}
avgHomeState={props.avgHomeState}
avgHomeUS={props.avgHomeUS}
Expand Down
72 changes: 72 additions & 0 deletions src/components/Results/EnergyScore/needle.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import React, { useState, useEffect, useRef } from 'react';

const Needle = ({ desiredScore, scoreLabel, width, height }) => {
const needleRef = useRef(null);
const [angle, setAngle] = useState(150);
const [score, setScore] = useState(0);
const [radius, setRadius] = useState(0);
const [center, setCenter] = useState({ x: 0, y: 0 });
const startAngle = 140;

const calculateEndAngle = (score) => {
const effectiveScore = Math.min(100, Math.max(0, score));
let rawEndAngle;
if (effectiveScore <= 33) {
rawEndAngle = startAngle + effectiveScore / 33 * 80;
} else if (effectiveScore <= 66) {
rawEndAngle = startAngle + 90 + (effectiveScore - 33) / 33 * 80;
} else {
rawEndAngle = startAngle + 180 + (effectiveScore - 66) / 33 * 80
}
return rawEndAngle;
};

const endAngle = calculateEndAngle(desiredScore);

const calculatePosition = (angle) => {
const x = center.x + radius * Math.cos(angle * Math.PI / 180);
const y = center.y + radius * Math.sin(angle * Math.PI / 180);
return { x, y };
};

const calculateRotation = (angle) => {
return angle + 90;
};

useEffect(() => {
setAngle(endAngle);
setScore(desiredScore);
}, [endAngle]);

useEffect(() => {
setRadius(0.75 * Math.min(width, height) / 2);
setCenter({ x: width / 2, y: height / 2 });
}, [width, height]);

const position = calculatePosition(angle);
const rotation = calculateRotation(angle);

return (
<div style={{ width: '100%', height: '100%' }} ref={needleRef}>
<svg width="100%" height="100%" style={{ position: 'absolute', left: 0, top: 0, zIndex: 20 }}>
<circle cx={center.x} cy={center.y} r={radius} fill='white'></circle>
</svg>
<svg width="100%" height="100%" style={{ position: 'absolute', left: 0, top: 0, zIndex: 25 }}>
<circle cx={center.x} cy={center.y} r={0.85 * radius} stroke="#ddd" strokeWidth={2} fill='white' ></circle>
</svg>
<svg width="100%" height="100%" style={{ position: 'absolute', left: 0, top: 0, zIndex: 10 }}>
<polygon
points={`${position.x}, ${position.y - 7} ${position.x - 7},${position.y + 5} ${position.x + 7},${position.y + 5}`}
fill="black"
transform={`rotate(${rotation} ${position.x} ${position.y})`}
/>
</svg>
<div style={{ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, zIndex: 30, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
<span style={{ fontSize: "40px", fontWeight: 'bold' }}>{parseInt(score)}</span>
<span style={{ fontWeight: 'bold' }}>{scoreLabel}</span>
</div>
</div >
);
};

export default Needle;
82 changes: 38 additions & 44 deletions src/components/Results/EnergyScore/scorering.jsx
Original file line number Diff line number Diff line change
@@ -1,55 +1,49 @@
import React from 'react';
import { PieChart, Pie, Cell, ResponsiveContainer } from 'recharts';
import React, { useState, useEffect, useRef } from 'react';
import Needle from './needle';
import Arc from './arc';
import backgroundImage from '../../../assets/dial_bg.png';

const COLORS = ['#f00', '#ffbf00', '#00ff00'];

const ScoreRing = ({ value, scoreLabel }) => {
const dialRef = useRef(null);
const score = Math.min(Math.max(value, 0), 100);
const colorIndex = score === 100 ? COLORS.length - 1 : Math.floor(score / (100 / COLORS.length));
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
useEffect(() => {
const getDimensions = () => {
if (dialRef.current) {
setWidth(dialRef.current.offsetWidth);
setHeight(dialRef.current.offsetHeight);
}
};
getDimensions();

const data = [
{ value: score, fill: COLORS[colorIndex] },
{ value: 100 - score, fill: '#ccc' }
];
const resizeObserver = new ResizeObserver(getDimensions);
if (dialRef.current) {
resizeObserver.observe(dialRef.current);
}

return () => {
if (dialRef.current) {
resizeObserver.unobserve(dialRef.current);
}
};
}, []);

return (
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={data}
dataKey="value"
cx="50%"
cy="50%"
innerRadius="60%"
outerRadius="80%"
startAngle={90}
endAngle={-270}
isAnimationActive={false}
>
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.fill} />
))}
</Pie>
<text
x="50%"
y="50%"
textAnchor="middle"
dominantBaseline="middle"
style={{ fontSize: '1.5em', fontWeight: 'bold' }}
>
{score}
</text>
<text
x="50%"
y="60%"
textAnchor="middle"
dominantBaseline="middle"
style={{ fontSize: '1em' }}
>
{scoreLabel}
</text>
</PieChart>
</ResponsiveContainer>
<div style={{
width: '100%',
height: '100%',
backgroundImage: `url(${backgroundImage})`,
backgroundRepeat: 'no-repeat',
backgroundSize: 'contain',
backgroundPosition: 'center',
position: 'relative'
}} ref={dialRef}>
<Needle desiredScore={score} scoreLabel={scoreLabel} width={width} height={height} />
<Arc score={score} width={width} height={height} />
</div >
);
};

Expand Down
Loading