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

feat(ui): use recharts achieve better responsiveness #3

Merged
merged 1 commit into from
Mar 14, 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
211 changes: 141 additions & 70 deletions components/poll-process-result-section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,84 +2,99 @@ import NewPollConfirmDialog from '@/components/new-poll-confirm-dialog';
import Spinner from '@/components/spinner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
updateChartResultParam,
useChartConfig,
} from '@/hooks/use-chart-config';
import { useChartConfig } from '@/hooks/use-chart-config';
import { useFetchLiveChat } from '@/hooks/use-fetch-livechat';
import { cn } from '@/lib/utils';
import { usePollAppStore } from '@/stores/store';
import {
BarElement,
CategoryScale,
Chart as ChartJS,
Legend,
LinearScale,
Title,
Tooltip,
} from 'chart.js';
import { StopCircleIcon } from 'lucide-react';
import { useCallback, useEffect, useRef } from 'react';
import { Bar } from 'react-chartjs-2';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { BrowserView, MobileView, isMobile } from 'react-device-detect';
import {
Bar,
BarChart,
CartesianGrid,
Cell,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import MotionContainer from './motion-container';
import PollSummarySubCard from './poll-summary-subcard';

ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
import SuppressDefaultPropsWarning from './suppress-default-props-warning';

const PollProcessResultSection = () => {
const {
pollAppState,
changePollAppState,
newPollReset,
pollResultSummary,
setPollResultSummary,
numOfOptions,
} = usePollAppStore();
const { chartOptions, chartInitData, sortChartResult } = useChartConfig();
const barChartRef = useRef<ChartJS<'bar', number[], string>>(null);

const updateChartInPolling = useCallback(
(data: number[]) => {
if (barChartRef.current) {
barChartRef.current.data.datasets[0].data = data;
barChartRef.current.update();
setPollResultSummary(data);
}
},
[setPollResultSummary]
);
const { chartInitData } = useChartConfig();

const updateChartPollResult = useCallback((param: updateChartResultParam) => {
if (barChartRef.current) {
barChartRef.current.data.datasets[0].data = param.newArrayData;
barChartRef.current.data.datasets[0].backgroundColor = param.newBarColor;
barChartRef.current.data.datasets[0].borderColor = param.newBorderColor;
barChartRef.current.data.labels = param.newArrayLabel;
barChartRef.current.update();
}
}, []);

useFetchLiveChat({ updateChart: updateChartInPolling });
useFetchLiveChat();

const handleProceedNewPoll = useCallback(() => {
newPollReset();
const divElement = document.getElementById('prepare-section-card');
if (divElement) {
divElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [newPollReset]);

const cardRef = useRef<HTMLDivElement>(null);

useEffect(() => {
if (cardRef.current) {
cardRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' });
cardRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [cardRef]);

const enableRankedChartResult = useMemo(() => {
return pollAppState === 'stop';
}, [pollAppState]);

const barChartData = useMemo(() => {
if (pollResultSummary.length === 0) {
return new Array(numOfOptions).fill(0).map((value, index) => {
return {
name: String(index + 1),
color: chartInitData.datasets[0].backgroundColor[index],
value,
};
});
}

if (enableRankedChartResult) {
const rankedResult = pollResultSummary
.map((value, index) => {
return {
name: String(index + 1),
color: chartInitData.datasets[0].backgroundColor[index],
value,
};
})
.sort((a, b) => (a.value === b.value ? 0 : a.value > b.value ? -1 : 1));

rankedResult[0].name = `👑${rankedResult[0].name}`;
return rankedResult;
}

return pollResultSummary.map((value, index) => {
return {
name: String(index + 1),
color: chartInitData.datasets[0].backgroundColor[index],
value,
};
});
}, [
chartInitData.datasets,
enableRankedChartResult,
numOfOptions,
pollResultSummary,
]);

return (
<MotionContainer
whileInView='onscreen'
Expand All @@ -91,7 +106,7 @@ const PollProcessResultSection = () => {
'h-full': isMobile,
})}
>
<Card ref={cardRef} className='h-full w-full'>
<Card ref={cardRef} className='h-full w-full' id='process-section-card'>
<CardHeader>
{pollAppState === 'stop' ? (
<CardTitle className='font-extrabold uppercase text-primary'>
Expand All @@ -105,30 +120,87 @@ const PollProcessResultSection = () => {
)}
</CardHeader>
<CardContent className='flex flex-col gap-2'>
<SuppressDefaultPropsWarning />
<BrowserView>
<div className='flex gap-8'>
<PollSummarySubCard />
<div className={cn('w-full h-full mt-4')}>
<Bar
ref={barChartRef}
options={chartOptions}
data={chartInitData}
height='100%'
redraw
/>
</div>
<ResponsiveContainer width='100%' aspect={2.0}>
<BarChart data={barChartData} layout='vertical'>
<CartesianGrid strokeDasharray='3 3' stroke='#e11d48' />
<XAxis hide axisLine={false} type='number' />
<YAxis
yAxisId={0}
dataKey='name'
type='category'
axisLine={false}
tickLine={false}
tick={true}
/>
<YAxis
orientation='right'
yAxisId={1}
dataKey='value'
type='category'
axisLine={false}
tickLine={false}
tickFormatter={(value) => value.toLocaleString()}
/>
<Tooltip
cursor={{ fill: 'transparent' }}
labelStyle={{ color: 'black' }}
contentStyle={{
border: 'transparent',
borderRadius: '8px',
background: 'lightgray',
}}
/>
<Bar minPointSize={2} barSize={20} dataKey='value'>
{barChartData.map((d, _idx) => {
return <Cell key={d.name} fill={d.color} />;
})}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
</BrowserView>
<MobileView>
{/* <div className={cn('w-full h-full')}>
<Bar
ref={barChartRef}
options={chartOptions}
data={chartInitData}
height='300px'
redraw
/>
</div> FIXME: responsive here sucks!!!*/}
<ResponsiveContainer width='100%' aspect={0.5}>
<BarChart data={barChartData} layout='vertical'>
<CartesianGrid strokeDasharray='3 3' stroke='#e11d48' />
<XAxis hide axisLine={false} type='number' />
<YAxis
yAxisId={0}
dataKey='name'
type='category'
axisLine={false}
tickLine={false}
tick={true}
/>
<YAxis
orientation='right'
yAxisId={1}
dataKey='value'
type='category'
axisLine={false}
tickLine={false}
tickFormatter={(value) => value.toLocaleString()}
/>
<Tooltip
cursor={{ fill: 'transparent' }}
labelStyle={{ color: 'black' }}
contentStyle={{
border: 'transparent',
borderRadius: '8px',
background: 'lightgray',
}}
/>
<Bar minPointSize={2} barSize={20} dataKey='value'>
{barChartData.map((d, _idx) => {
return <Cell key={d.name} fill={d.color} />;
})}
</Bar>
</BarChart>
</ResponsiveContainer>
<div className='flex items-center justify-center -ml-2'>
<PollSummarySubCard />
</div>
Expand All @@ -141,7 +213,6 @@ const PollProcessResultSection = () => {
className='mt-8 flex w-32 self-end'
onClick={() => {
changePollAppState('stop');
sortChartResult(updateChartPollResult);
}}
>
Stop
Expand Down
11 changes: 10 additions & 1 deletion components/prepare-section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const PrepareSection = () => {

return (
<MotionContainer className={cn({ grayscale: pollAppState != 'prepare' })}>
<Card className=''>
<Card id='prepare-section-card'>
<CardHeader>
<CardTitle className='font-extrabold uppercase text-primary'>
1️⃣ Prepare
Expand Down Expand Up @@ -113,6 +113,15 @@ const PrepareSection = () => {
changePollAppState('start');
setPollResultSummary(new Array(numOfOptions).fill(0));
setPollStartDateTime(dayjs());
const divElement = document.getElementById(
'process-section-card'
);
if (divElement) {
divElement.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
}
}}
>
Start Poll
Expand Down
29 changes: 29 additions & 0 deletions components/suppress-default-props-warning.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use client';

import React, { useEffect } from 'react';

/**
* FIXME: This component is workaround for recharts warning
* see: https://github.com/recharts/recharts/issues/3615
*/
const SuppressDefaultPropsWarning: React.FC = () => {
useEffect(() => {
const originalConsoleError = console.error;

console.error = (...args: any[]) => {
if (typeof args[0] === 'string' && /defaultProps/.test(args[0])) {
return;
}

originalConsoleError(...args);
};

return () => {
console.error = originalConsoleError;
};
}, []);

return null;
};

export default SuppressDefaultPropsWarning;
Loading
Loading