react-chartjs-2#Doughnut JavaScript Examples

The following examples show how to use react-chartjs-2#Doughnut. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PullRequestChart.js    From developerPortfolio with MIT License 6 votes vote down vote up
render() {
    const data = {
      labels: ["Open", "Merged", "Closed"],
      datasets: [
        {
          data: [
            PullRequestData["open"],
            PullRequestData["merged"],
            PullRequestData["closed"],
          ],
          backgroundColor: ["#4CAF50", "#673AB7", "#FF5252"],
          hoverBackgroundColor: ["#4CAF50", "#673AB7", "#FF5252"],
        },
      ],
    };

    return (
      <div class="pr-chart">
        <Fade bottom duration={2000} distance="20px">
          <h2 className="pr-chart-header">Pull Request Distribution</h2>
        </Fade>
        <Doughnut
          data={data}
          options={{
            padding: "0",
            margin: "0",
            responsive: true,
            maintainAspectRatio: true,
            animation: {
              duration: 4000,
            },
          }}
        />
      </div>
    );
  }
Example #2
Source File: dountchart.js    From gedge-platform with Apache License 2.0 6 votes vote down vote up
render() {
        const data = {
            labels: [
                "Desktops",
                "Tablets"
            ],
            datasets: [
                {
                    data: [300, 210],
                    backgroundColor: [
                        "#556ee6",
                        "#ebeff2"
                    ],
                    hoverBackgroundColor: [
                        "#556ee6",
                        "#ebeff2"
                    ],
                    hoverBorderColor: "#fff"
                }]
        };
        return (
            <React.Fragment>
                <Doughnut width={474} height={260} data={data}/>
            </React.Fragment>
        );
    }
Example #3
Source File: Charts.js    From windmill-dashboard-react with MIT License 6 votes vote down vote up
function Charts() {
  return (
    <>
      <PageTitle>Charts</PageTitle>

      <div className="grid gap-6 mb-8 md:grid-cols-2">
        <ChartCard title="Doughnut">
          <Doughnut {...doughnutOptions} />
          <ChartLegend legends={doughnutLegends} />
        </ChartCard>

        <ChartCard title="Lines">
          <Line {...lineOptions} />
          <ChartLegend legends={lineLegends} />
        </ChartCard>

        <ChartCard title="Bars">
          <Bar {...barOptions} />
          <ChartLegend legends={barLegends} />
        </ChartCard>
      </div>
    </>
  )
}
Example #4
Source File: Doughnut.jsx    From crypto-manager with MIT License 6 votes vote down vote up
render() {
		return (
			<div>
				<Doughnut data={this.state.Data} width={400} height={400}
							options={{
								responsive: true,
								maintainAspectRatio: true }}
								onElementsClick={elems => {
									try {
										console.log(elems[0]._index);
									} catch (error) {
										console.log(error)
									}
								}} />
			</div>
		)
	}
Example #5
Source File: DoughnutChart.js    From indeplot with GNU General Public License v3.0 6 votes vote down vote up
export function DoughnutChart(props) {

  function generateGraph() {
    const colorVal = `rgba(${props.color.r},${props.color.g},${props.color.b},${props.color.a})`;
    return {
      labels: props.labels,
      datasets: [
        {
          label: props.title,
          fill: false,
          lineTension: 0.5,
          backgroundColor: colorVal,
          borderColor: 'rgba(0,0,0,1)',
          borderWidth: 2,
          data: props.data
        }
      ]
    }
  }

  return (
    <Doughnut data={generateGraph} />)
}
Example #6
Source File: PullRequestChart.js    From masterPortfolio with MIT License 6 votes vote down vote up
render() {
    const data = {
      labels: ["Open", "Merged", "Closed"],
      datasets: [
        {
          data: [
            PullRequestData["open"],
            PullRequestData["merged"],
            PullRequestData["closed"],
          ],
          backgroundColor: ["#28a745", "#6f42c1", "#d73a49"],
          hoverBackgroundColor: ["#28a745dd", "#6f42c1dd", "#d73a49dd"],
        },
      ],
    };

    return (
      <div className="pr-chart">
        <Fade bottom duration={2000} distance="20px">
          <h2 className="pr-chart-header">Pull Request Distribution</h2>
        </Fade>
        <Doughnut
          data={data}
          options={{
            padding: "0",
            margin: "0",
            responsive: true,
            maintainAspectRatio: true,
            animation: {
              duration: 4000,
            },
          }}
        />
      </div>
    );
  }
Example #7
Source File: IssueChart.js    From masterPortfolio with MIT License 6 votes vote down vote up
render() {
    const data = {
      labels: ["Open", "Closed"],
      datasets: [
        {
          data: [IssueData["open"], IssueData["closed"]],
          backgroundColor: ["#28a745", "#d73a49"],
          hoverBackgroundColor: ["#28a745dd", "#d73a49dd"],
        },
      ],
    };

    return (
      <div className="issue-chart">
        <Fade bottom duration={2000} distance="20px">
          <h2 className="issue-chart-header">Issue Distribution</h2>
        </Fade>
        <Doughnut
          data={data}
          options={{
            margin: "0",
            padding: "0",
            responsive: true,
            maintainAspectRatio: true,
            animation: {
              duration: 4000,
            },
          }}
        />
      </div>
    );
  }
Example #8
Source File: PullRequestChart.js    From portfolio with MIT License 6 votes vote down vote up
render() {
    const data = {
      labels: ["Open", "Merged", "Closed"],
      datasets: [
        {
          data: [
            PullRequestData["open"],
            PullRequestData["merged"],
            PullRequestData["closed"],
          ],
          backgroundColor: ["#28a745", "#6f42c1", "#d73a49"],
          hoverBackgroundColor: ["#28a745dd", "#6f42c1dd", "#d73a49dd"],
        },
      ],
    };

    return (
      <div class="pr-chart">
        <Fade bottom duration={2000} distance="20px">
          <h2 className="pr-chart-header">Pull Request Distribution</h2>
        </Fade>
        <Doughnut
          data={data}
          options={{
            padding: "0",
            margin: "0",
            responsive: true,
            maintainAspectRatio: true,
            animation: {
              duration: 4000,
            },
          }}
        />
      </div>
    );
  }
Example #9
Source File: IssueChart.js    From portfolio with MIT License 6 votes vote down vote up
render() {
    const data = {
      labels: ["Open", "Closed"],
      datasets: [
        {
          data: [IssueData["open"], IssueData["closed"]],
          backgroundColor: ["#28a745", "#d73a49"],
          hoverBackgroundColor: ["#28a745dd", "#d73a49dd"],
        },
      ],
    };

    return (
      <div class="issue-chart">
        <Fade bottom duration={2000} distance="20px">
          <h2 className="issue-chart-header">Issue Distribution</h2>
        </Fade>
        <Doughnut
          data={data}
          options={{
            margin: "0",
            padding: "0",
            responsive: true,
            maintainAspectRatio: true,
            animation: {
              duration: 4000,
            },
          }}
        />
      </div>
    );
  }
Example #10
Source File: DaysChart.test.js    From pomodor with MIT License 5 votes vote down vote up
jest.mock('react-chartjs-2', () => ({
  Doughnut: () => null,
}))
Example #11
Source File: DoughnutChart.js    From DMS_React with GNU Affero General Public License v3.0 5 votes vote down vote up
DoughnutChart = () => {

  return (
    <Doughnut data={data} options={options} height={200}/>
  );
}
Example #12
Source File: Chart.js    From gitpedia with MIT License 5 votes vote down vote up
DoughnutChart = () => {
    const themeContext = useContext(ThemeContext);

    const data = {
        labels: [],
        datasets: [
            {
                label: "",
                data: [],
                backgroundColor: bgColor,
                borderWidth: 0,
            },
        ],
    };

    return (
        <LanguageContext.Consumer>
            {(context) => {
                const LIMIT = 10;
                let labels = context.map((obj) => obj.label);

                // If more than LIMIT languages then reduce it to the limit
                if (labels.length >= LIMIT) {
                    labels = labels.slice(0, LIMIT);
                }
                const value = context.map((obj) => obj.value).slice(0, LIMIT);
                data.labels = labels;
                data.datasets[0].data = value;

                return (
                    <Doughnut
                        data={data}
                        options={{
                            maintainAspectRatio: false,
                            responsive: true,
                            title: {
                                display: false,
                            },
                            legend: {
                                // display: false,
                                position: "bottom",
                                labels: {
                                    fontColor: themeContext.textColor,
                                }
                            },
                        }}
                    />
                );
            }}
        </LanguageContext.Consumer>
    );
}
Example #13
Source File: handle-doughnut-bar.js    From horondi_admin with MIT License 5 votes vote down vote up
handleDoughnutBar = (mainData, options) =>
  mainData.datasets[0].data.length ? (
    <Doughnut data={mainData} options={options} redraw />
  ) : (
    <StatisticError />
  )
Example #14
Source File: DaysChart.test.js    From pomodor with MIT License 5 votes vote down vote up
describe('<DaysChart />', () => {
  const shallow = createShallow()
  const createWrapper = () => {
    return shallow(<DaysChart />)
  }

  const createStore = () => {
    const store = {
      settings: {
        firstDayOfTheWeek: 'Monday',
        darkMode: false,
      },
      sessions,
    }

    jest
      .spyOn(redux, 'useSelector')
      .mockImplementation((callback) => callback(store))

    return store
  }

  beforeEach(() => {
    jest.clearAllMocks()
  })

  test('should render <DaysChart /> correctly', () => {
    createStore()
    expect(createWrapper()).toMatchSnapshot()
  })

  test('should render <Doughnut /> correctly', () => {
    createStore()
    expect(createWrapper().find(Doughnut).exists()).toBe(true)
  })

  test('there should be 7 chart labels', () => {
    createStore()
    expect(createWrapper().find(Doughnut).prop('data').labels.length).toBe(7)
  })

  test('should open menu on button click', () => {
    createStore()
    const wrapper = createWrapper()

    wrapper.find(CardHeader).prop('action').props.onClick({ currentTarget: {} })
    expect(wrapper.find(Menu).prop('open')).toBe(true)
  })
})
Example #15
Source File: LabelsChart.test.js    From pomodor with MIT License 5 votes vote down vote up
jest.mock('react-chartjs-2', () => ({
  Doughnut: () => null,
}))
Example #16
Source File: LabelsChart.test.js    From pomodor with MIT License 5 votes vote down vote up
describe('<LabelsChart />', () => {
  let mount
  const createWrapper = () => {
    return mount(<LabelsChart />)
  }

  const createStore = () => {
    const store = {
      settings: {
        firstDayOfTheWeek: 'Monday',
        darkMode: false,
      },
      labels: {
        data: labels,
      },
      sessions,
    }

    jest
      .spyOn(redux, 'useSelector')
      .mockImplementation((callback) => callback(store))

    return store
  }

  beforeEach(() => {
    mount = createMount()
    jest.clearAllMocks()
  })

  afterEach(() => {
    mount.cleanUp()
  })

  test('should render <LabelsChart /> correctly', () => {
    createStore()
    expect(createWrapper()).toMatchSnapshot()
  })

  test('should render <Doughnut /> correctly', () => {
    createStore()
    expect(createWrapper().find(Doughnut).exists()).toBe(true)
  })

  test('there should be labels.length + 1 labels', () => {
    createStore()

    expect(createWrapper().find(Doughnut).prop('data').labels.length).toBe(
      labels.length + 1
    )
  })

  test('should open menu on button click', () => {
    createStore()
    const wrapper = createWrapper()

    wrapper.find(IconButton).simulate('click')
    expect(wrapper.find(Menu).prop('open')).toBe(true)
  })
})
Example #17
Source File: index.js    From gobench with Apache License 2.0 5 votes vote down vote up
ChartsChartjs = () => {
  return (
    <div>
      <Helmet title="Charts / Chartjs" />
      <div className="kit__utils__heading">
        <h5>
          <span className="mr-3">Charts / Chartjs</span>
          <a
            href="http://www.chartjs.org/"
            rel="noopener noreferrer"
            target="_blank"
            className="btn btn-sm btn-light"
          >
            Official Documentation
            <i className="fe fe-corner-right-up" />
          </a>
        </h5>
      </div>
      <div className="card">
        <div className="card-body">
          <div className="row">
            <div className="col-xl-6 col-lg-12">
              <h5 className="mb-4">
                <strong>Line Chart</strong>
              </h5>
              <div className="mb-5">
                <Line data={lineData} options={lineOptions} width={400} height={200} />
              </div>
            </div>
            <div className="col-xl-6 col-lg-12">
              <h5 className="mb-4">
                <strong>Bar Chart</strong>
              </h5>
              <div className="mb-5">
                <Bar data={barData} options={barOptions} width={400} height={200} />
              </div>
            </div>
          </div>
          <div className="row">
            <div className="col-xl-6 col-lg-12">
              <h5 className="mb-4">
                <strong>Radar Chart</strong>
              </h5>
              <div className="mb-5">
                <Radar data={radarData} options={radarOptions} width={400} height={200} />
              </div>
            </div>
            <div className="col-xl-6 col-lg-12">
              <h5 className="mb-4">
                <strong>Polar Area Chart</strong>
              </h5>
              <div className="mb-5">
                <Polar data={polarData} options={polarOptions} width={400} height={200} />
              </div>
            </div>
          </div>
          <div className="row">
            <div className="col-xl-6 col-lg-12">
              <h5 className="mb-4">
                <strong>Pie Chart</strong>
              </h5>
              <div className="mb-5">
                <Pie data={pieData} options={pieOptions} width={400} height={200} />
              </div>
            </div>
            <div className="col-xl-6 col-lg-12">
              <h5 className="mb-4">
                <strong>Doughnut Chart</strong>
              </h5>
              <div className="mb-5">
                <Doughnut data={doughnutData} options={doughnutOptions} width={400} height={200} />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
Example #18
Source File: Charts.js    From ingress-cycle-stats with MIT License 5 votes vote down vote up
export function ScoreDoughnut({ data }) {
  const [visable, setVisable] = useState(false)

  const options = {
    responsive: true,
          maintainAspectRatio: false,
    legend: {
      display: true,
    },
    tooltips: {
      enabled: true,
    },
  }

  return (
    <VisibilitySensor
      partialVisibility
      onChange={isVisible => setVisable(isVisible)}
    >
      <ChartSpacer height="150px">
        {visable && (
          <Doughnut
          height={250}
            data={{
              labels: ["Resistance", "Enlightened"],
              datasets: [
                {
                  borderColor: "#000",
                  data: [data.resistanceWins, data.enlightenedWins],
                  backgroundColor: [COLOR_RESISTANCE, COLOR_ENLIGHTENED],
                },
              ],
            }}
            options={options}
          />
        )}
      </ChartSpacer>
    </VisibilitySensor>
  )
}
Example #19
Source File: pie-chart-percent.js    From covid19-dashboard with MIT License 5 votes vote down vote up
PieChartPercent = ({data, labels, colors, height}) => {
  const chartRef = useRef(null)
  const chart = {
    labels,
    datasets: [{
      data,
      backgroundColor: colors,
      _meta: {}
    }]
  }

  const options = {
    responsive: true,
    events: false,
    animation: {
      duration: 1000,
      easing: 'easeOutQuart',
      onComplete: animation => {
        const {ctx} = animation.chart
        const {data} = chartRef.current.props
        ctx.font = Chart.helpers.fontString(15, 'bold', Chart.defaults.global.defaultFontFamily)
        ctx.textAlign = 'center'
        ctx.textBaseline = 'bottom'
        ctx.context = {}
        data.datasets.forEach(dataset => {
          for (let i = 0; i < dataset.data.length; i++) {
            const model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model
            const total = dataset._meta[Object.keys(dataset._meta)[0]].total
            const midRadius = model.innerRadius + ((model.outerRadius - model.innerRadius) / 2)
            const startAngle = model.startAngle
            const endAngle = model.endAngle
            const midAngle = startAngle + ((endAngle - startAngle) / 2)
            const x = midRadius * Math.cos(midAngle)
            const y = midRadius * Math.sin(midAngle)
            ctx.fillStyle = '#fff'
            const percent = String(Math.round(dataset.data[i] / total * 100)) + '%'
            ctx.fillText(percent, model.x + x, model.y + y + 15)
          }
        })
      }
    }
  }

  return (
    <Doughnut ref={chartRef} data={chart} options={options} height={height} />
  )
}
Example #20
Source File: ChartJs.js    From Purple-React with MIT License 5 votes vote down vote up
render() {
        return (
            <div>
                <div className="page-header">
                    <h3 className="page-title">
                        Chart-js
                    </h3>
                    <nav aria-label="breadcrumb">
                        <ol className="breadcrumb">
                        <li className="breadcrumb-item"><a href="!#" onClick={event => event.preventDefault()}>Charts</a></li>
                        <li className="breadcrumb-item active" aria-current="page">Chart-js</li>
                        </ol>
                    </nav>
                </div>
                <div className="row">
                    <div className="col-md-6 grid-margin stretch-card">
                        <div className="card">
                            <div className="card-body">
                                <h4 className="card-title">Line Chart</h4>
                                <Line data={this.data} options={this.options} />
                            </div>
                        </div>
                    </div>
                    <div className="col-md-6 grid-margin stretch-card">
                        <div className="card">
                            <div className="card-body">
                                <h4 className="card-title">Bar Chart</h4>
                                <Bar data={this.data} options={this.options} />    
                            </div>
                        </div>
                    </div>
                </div>
                <div className="row">
                    <div className="col-md-6 grid-margin stretch-card">
                        <div className="card">
                            <div className="card-body">
                                <h4 className="card-title">Area Chart</h4>
                                <Line data={this.areaData} options={this.areaOptions} />
                            </div>
                        </div>
                    </div>
                    <div className="col-md-6 grid-margin stretch-card">
                        <div className="card">
                            <div className="card-body">
                                <h4 className="card-title">Doughnut Chart</h4>
                                <Doughnut data={this.doughnutPieData} options={this.doughnutPieOptions} />
                            </div>
                        </div>
                    </div>
                </div>
                <div className="row">
                    <div className="col-md-6 grid-margin stretch-card">
                        <div className="card">
                            <div className="card-body">
                                <h4 className="card-title">Pie Chart</h4>
                                <Pie data={this.doughnutPieData} options={this.doughnutPieOptions} />                                
                            </div>
                        </div>
                    </div>
                    <div className="col-md-6 grid-margin stretch-card">
                        <div className="card">
                            <div className="card-body">
                                <h4 className="card-title">Scatter Chart</h4>
                                <Scatter data={this.scatterChartData} options={this.scatterChartOptions} />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
Example #21
Source File: Chart.js    From management-center with Apache License 2.0 5 votes vote down vote up
Chart = ({ className, title, data, labels, dataDescriptions, ...rest }) => {
	const classes = useStyles();
	const theme = useTheme();

	const options = {
		animation: false,
		cutoutPercentage: 80,
		layout: { padding: 0 },
		legend: {
			display: false
		},
		maintainAspectRatio: false,
		responsive: true,
		tooltips: {
			backgroundColor: theme.palette.background.default,
			bodyFontColor: theme.palette.text.secondary,
			borderColor: theme.palette.divider,
			borderWidth: 1,
			enabled: true,
			footerFontColor: theme.palette.text.secondary,
			intersect: false,
			mode: 'index',
			titleFontColor: theme.palette.text.primary
		}
	};

	return (
		<Card className={clsx(classes.root, className)} {...rest}>
			<CardHeader title={title} />
			<Divider />
			<CardContent>
				<Box height={300} position="relative">
					<Doughnut data={data} options={options} />
				</Box>
				<Box display="flex" justifyContent="center" mt={2}>
					{dataDescriptions.map(({ color, icon: Icon, title, value }) => (
						<Box key={title} p={1} textAlign="center">
							<Icon color="action" />
							<Typography color="textPrimary" variant="body1">
								{title}
							</Typography>
							<Typography style={{ color }} variant="h3">
								{value}%
							</Typography>
						</Box>
					))}
				</Box>
			</CardContent>
		</Card>
	);
}
Example #22
Source File: genderchart.js    From covid19Nepal-react with MIT License 5 votes vote down vote up
function GenderChart(props) {
  let male = 0;
  let female = 0;

  if (!props.data || props.data.length === 0) {
    return <div></div>;
  }

  props.data.forEach((patient) => {
    if (patient.gender === 'M') {
      male++;
    } else if (patient.gender === 'F') {
      female++;
    }
  });

  const chartData = {
    datasets: [
      {
        data: [male, female],
        backgroundColor: ['#6497f3', '#ea6e9a'],
        label: 'Hola',
      },
    ],
    labels: ['Male', 'Female'],
  };

  const chartOptions = deepmerge(defaultOptions, {
    tooltips: {
      mode: 'point',
      position: 'nearest',
      callbacks: {
        label: function (tooltipItem, data) {
          const dataset = data.datasets[tooltipItem.datasetIndex];
          const meta = dataset._meta[Object.keys(dataset._meta)[0]];
          const total = meta.total;
          const currentValue = dataset.data[tooltipItem.index];
          const percentage = parseFloat(
            ((currentValue / total) * 100).toFixed(1)
          );
          return formatNumber(currentValue) + ' (' + percentage + '%)';
        },
        title: function (tooltipItem, data) {
          return data.labels[tooltipItem[0].index];
        },
      },
    },
  });

  return (
    <div className="charts-header">
      <div className="chart-title">{props.title}</div>
      <div className="chart-content doughnut">
        <Doughnut data={chartData} options={chartOptions} />
      </div>
      <div className="chart-note">
        Sample size: {formatNumber(male + female)} patients
      </div>
    </div>
  );
}
Example #23
Source File: Dashboard.js    From Purple-React with MIT License 4 votes vote down vote up
render () {
    return (
      <div>
        <div className="proBanner">
          <div>
            <span className="d-flex align-items-center purchase-popup">
              <p>Get tons of UI components, Plugins, multiple layouts, 20+ sample pages, and more!</p>
              <a href="https://www.bootstrapdash.com/product/purple-react/?utm_source=organic&utm_medium=banner&utm_campaign=free-preview" rel="noopener noreferrer" target="_blank" className="btn btn-sm purchase-button ml-auto">Check Pro Version</a>
              <i className="mdi mdi-close bannerClose" onClick={this.toggleProBanner}></i>
            </span>
          </div>
        </div>
        <div className="page-header">
          <h3 className="page-title">
            <span className="page-title-icon bg-gradient-primary text-white mr-2">
              <i className="mdi mdi-home"></i>
            </span> Dashboard </h3>
          <nav aria-label="breadcrumb">
            <ul className="breadcrumb">
              <li className="breadcrumb-item active" aria-current="page">
                <span></span>Overview <i className="mdi mdi-alert-circle-outline icon-sm text-primary align-middle"></i>
              </li>
            </ul>
          </nav>
        </div>
        <div className="row">
          <div className="col-md-4 stretch-card grid-margin">
            <div className="card bg-gradient-danger card-img-holder text-white">
              <div className="card-body">
                <img src={require("../../assets/images/dashboard/circle.svg")} className="card-img-absolute" alt="circle" />
                <h4 className="font-weight-normal mb-3">Weekly Sales <i className="mdi mdi-chart-line mdi-24px float-right"></i>
                </h4>
                <h2 className="mb-5">$ 15,0000</h2>
                <h6 className="card-text">Increased by 60%</h6>
              </div>
            </div>
          </div>
          <div className="col-md-4 stretch-card grid-margin">
            <div className="card bg-gradient-info card-img-holder text-white">
              <div className="card-body">
                <img src={require("../../assets/images/dashboard/circle.svg")} className="card-img-absolute" alt="circle" />
                <h4 className="font-weight-normal mb-3">Weekly Orders <i className="mdi mdi-bookmark-outline mdi-24px float-right"></i>
                </h4>
                <h2 className="mb-5">45,6334</h2>
                <h6 className="card-text">Decreased by 10%</h6>
              </div>
            </div>
          </div>
          <div className="col-md-4 stretch-card grid-margin">
            <div className="card bg-gradient-success card-img-holder text-white">
              <div className="card-body">
                <img src={require("../../assets/images/dashboard/circle.svg")} className="card-img-absolute" alt="circle" />
                <h4 className="font-weight-normal mb-3">Visitors Online <i className="mdi mdi-diamond mdi-24px float-right"></i>
                </h4>
                <h2 className="mb-5">95,5741</h2>
                <h6 className="card-text">Increased by 5%</h6>
              </div>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-md-7 grid-margin stretch-card">
            <div className="card">
              <div className="card-body">
                <div className="clearfix mb-4">
                  <h4 className="card-title float-left">Visit And Sales Statistics</h4>
                  <div id="visit-sale-chart-legend" className="rounded-legend legend-horizontal legend-top-right float-right">
                    <ul>
                      <li>
                        <span className="legend-dots bg-primary">
                        </span>CHN
                      </li>
                      <li>
                        <span className="legend-dots bg-danger">
                        </span>USA
                      </li>
                      <li>
                        <span className="legend-dots bg-info">
                        </span>UK
                      </li>
                    </ul>
                  </div>
                </div>
                <Bar ref='chart' className="chartLegendContainer" data={this.state.visitSaleData} options={this.state.visitSaleOptions} id="visitSaleChart"/>
              </div>
            </div>
          </div>
          <div className="col-md-5 grid-margin stretch-card">
            <div className="card">
              <div className="card-body">
                <h4 className="card-title">Traffic Sources</h4>
                <Doughnut data={this.state.trafficData} options={this.state.trafficOptions} />
                <div id="traffic-chart-legend" className="rounded-legend legend-vertical legend-bottom-left pt-4">
                  <ul>
                    <li>
                      <span className="legend-dots bg-info"></span>Search Engines
                      <span className="float-right">30%</span>
                    </li>
                    <li>
                      <span className="legend-dots bg-success"></span>Direct Click
                      <span className="float-right">30%</span>
                    </li>
                    <li>
                      <span className="legend-dots bg-danger"></span>Bookmarks Click
                      <span className="float-right">40%</span>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-12 grid-margin">
            <div className="card">
              <div className="card-body">
                <h4 className="card-title">Recent Tickets</h4>
                <div className="table-responsive">
                  <table className="table">
                    <thead>
                      <tr>
                        <th> Assignee </th>
                        <th> Subject </th>
                        <th> Status </th>
                        <th> Last Update </th>
                        <th> Tracking ID </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td>
                          <img src={require("../../assets/images/faces/face1.jpg")} className="mr-2" alt="face" /> David Grey </td>
                        <td> Fund is not recieved </td>
                        <td>
                          <label className="badge badge-gradient-success">DONE</label>
                        </td>
                        <td> Dec 5, 2017 </td>
                        <td> WD-12345 </td>
                      </tr>
                      <tr>
                        <td>
                          <img src={require("../../assets/images/faces/face2.jpg")} className="mr-2" alt="face" /> Stella Johnson </td>
                        <td> High loading time </td>
                        <td>
                          <label className="badge badge-gradient-warning">PROGRESS</label>
                        </td>
                        <td> Dec 12, 2017 </td>
                        <td> WD-12346 </td>
                      </tr>
                      <tr>
                        <td>
                          <img src={require("../../assets/images/faces/face3.jpg")} className="mr-2" alt="face" /> Marina Michel </td>
                        <td> Website down for one week </td>
                        <td>
                          <label className="badge badge-gradient-info">ON HOLD</label>
                        </td>
                        <td> Dec 16, 2017 </td>
                        <td> WD-12347 </td>
                      </tr>
                      <tr>
                        <td>
                          <img src={require("../../assets/images/faces/face4.jpg")} className="mr-2" alt="face" /> John Doe </td>
                        <td> Loosing control on server </td>
                        <td>
                          <label className="badge badge-gradient-danger">REJECTED</label>
                        </td>
                        <td> Dec 3, 2017 </td>
                        <td> WD-12348 </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-lg-5 grid-margin stretch-card">
            <div className="card">
              <div className="card-body p-0 d-flex">
                <div className="dashboard-custom-date-picker">
                  <DatePicker inline selected={this.state.startDate}  onChange={this.handleChange}/>
                </div>
              </div>
            </div>
          </div>
          <div className="col-lg-7 grid-margin stretch-card">
            <div className="card">
              <div className="card-body">
                <h4 className="card-title">Recent Updates</h4>
                <div className="d-flex">
                  <div className="d-flex align-items-center mr-4 text-muted font-weight-light">
                    <i className="mdi mdi-account-outline icon-sm mr-2"></i>
                    <span>jack Menqu</span>
                  </div>
                  <div className="d-flex align-items-center text-muted font-weight-light">
                    <i className="mdi mdi-clock icon-sm mr-2"></i>
                    <span>October 3rd, 2018</span>
                  </div>
                </div>
                <div className="row mt-3">
                  <div className="col-6 pr-1">
                    <img src={require("../../assets/images/dashboard/img_1.jpg")} className="mb-2 mw-100 w-100 rounded" alt="face" />
                    <img src={require("../../assets/images/dashboard/img_4.jpg")} className="mw-100 w-100 rounded" alt="face" />
                  </div>
                  <div className="col-6 pl-1">
                    <img src={require("../../assets/images/dashboard/img_2.jpg")} className="mb-2 mw-100 w-100 rounded" alt="face" />
                    <img src={require("../../assets/images/dashboard/img_3.jpg")} className="mw-100 w-100 rounded" alt="face "/>
                  </div>
                </div>
                <div className="d-flex mt-5 align-items-start">
                  <img src={require("../../assets/images/faces/face3.jpg")} className="img-sm rounded-circle mr-3" alt="face" />
                  <div className="mb-0 flex-grow">
                    <h5 className="mr-2 mb-2">School Website - Authentication Module.</h5>
                    <p className="mb-0 font-weight-light">It is a long established fact that a reader will be distracted by the readable content of a page.</p>
                  </div>
                  <div className="ml-auto">
                    <i className="mdi mdi-heart-outline text-muted"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-xl-7 grid-margin stretch-card">
            <div className="card">
              <div className="card-body">
                <h4 className="card-title">Project Status</h4>
                <div className="table-responsive">
                  <table className="table">
                    <thead>
                      <tr>
                        <th> # </th>
                        <th> Name </th>
                        <th> Due Date </th>
                        <th> Progress </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td> 1 </td>
                        <td> Herman Beck </td>
                        <td> May 15, 2015 </td>
                        <td>
                          <ProgressBar variant="gradient-success" now={25}/>
                        </td>
                      </tr>
                      <tr>
                        <td> 2 </td>
                        <td> Messsy Adam </td>
                        <td> Jul 01, 2015 </td>
                        <td>
                        <ProgressBar variant="gradient-danger" now={75}/>
                        </td>
                      </tr>
                      <tr>
                        <td> 3 </td>
                        <td> John Richards </td>
                        <td> Apr 12, 2015 </td>
                        <td>
                        <ProgressBar variant="gradient-warning" now={90}/>
                        </td>
                      </tr>
                      <tr>
                        <td> 4 </td>
                        <td> Peter Meggik </td>
                        <td> May 15, 2015 </td>
                        <td>
                        <ProgressBar variant="gradient-primary" now={50}/>
                        </td>
                      </tr>
                      <tr>
                        <td> 5 </td>
                        <td> Edward </td>
                        <td> May 03, 2015 </td>
                        <td>
                        <ProgressBar variant="gradient-danger" now={50}/>
                        </td>
                      </tr>
                      <tr>
                        <td> 5 </td>
                        <td> Ronald </td>
                        <td> Jun 05, 2015 </td>
                        <td>
                        <ProgressBar variant="gradient-info" now={65}/>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
          <div className="col-xl-5 grid-margin stretch-card">
            <div className="card">
              <div className="card-body">
                <h4 className="card-title text-white">Todo</h4>
                <form  className="add-items d-flex" onSubmit={this.addTodo}>
                  <input 
                      type="text" 
                      className="form-control h-auto" 
                      placeholder="What do you need to do today?" 
                      value={this.state.inputValue} 
                      onChange={this.inputChangeHandler}
                      required />
                  <button type="submit" className="btn btn-gradient-primary font-weight-bold px-lg-4 px-3">Add</button>
                </form>
                <div className="list-wrapper">
                    <ul className="d-flex flex-column todo-list">
                        {this.state.todos.map((todo, index) =>{
                            return <ListItem 
                            isCompleted={todo.isCompleted}
                            changed={(event) => this.statusChangedHandler(event, index)}
                            key={todo.id}
                            remove={() => this.removeTodo(index) }
                            >{todo.task}</ListItem>
                        })}
                    </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div> 
    );
  }
Example #24
Source File: CurrentJobS.js    From GB-GCGC with MIT License 4 votes vote down vote up
render() {
    return (
      <div class="container-fluid">
        <Card className="Rounded p-3">
          <CardSubtitle align="left">
            <Row>
              <Col style={{"padding":"0px"}}>
                Current Job Suitability
              </Col>
              <Col style={{"textAlign":"end"}}>
                <Button
                  style={{"background-color": "rgb(42, 50, 75)"}}
                  onClick={() => {
                      this.handleModalcurrentjob();
                      }}
                >Edit
                </Button>
              </Col>
            </Row>
          </CardSubtitle>
          <hr></hr>
          <div class="container-fluid">
            <Row>
            <Col lg="4" md="6" sm="12">
         
                      <Doughnut data={{datasets: [{
                                data: [this.state.Analyst,100-this.state.Analyst],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      />Analyst
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state.CustomerSales,100-this.state.CustomerSales],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      />CustomerSales
            </Col>
            <Col lg="4" md="6" sm="12">
              <Doughnut data={{datasets: [{
                                data: [this.state.PlantEngineer,100-this.state.PlantEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Plant Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
              <Doughnut data={{datasets: [{
                                data: [this.state. RRDEngineer,100-this.state. RRDEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      />RRD Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state.NetworkEngineer,100-this.state.NetworkEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Network Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state. OperationsEngineer,100-this.state.OperationsEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Operations Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state.SoftwareDeveloper,100-this.state.SoftwareDeveloper],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Software Developer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state. SoftwareEngineer,100-this.state. SoftwareEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Software Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state. SoftwareTester,100-this.state.SoftwareTester],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      />Software Tester
            </Col>
          </Row>
          </div>
          <br></br>
          <Modal
            show={this.state.show}
            onHide={() => this.handleModalcurrentjob()}
          >
            <Modal.Header closeButton>Edit </Modal.Header>
            <form onSubmit={this.onSubmitCurrentJob}>
            <Modal.Body>
              <Table className="CurrentJobSEdit" responsive>
                <tr>
                  <td>Analyst</td>
                  <td>
                    <input type="text" name="Analyst" onChange={this.onChangeAnalyst} value={this.state.Analyst} />
                  </td>
                </tr>
                <tr>
                  <td>CostumerSales</td>
                  <td>
                    <input type="text" name="CustomerSales" onChange={this.onChangeCustomerSales} value={this.state.CustomerSales} />
                  </td>
                </tr>
                <tr>
                  <td>Plant Engineer</td>
                  <td>
                    <input type="text" name="PlantEngineer" onChange={this.onChangePlantEngineer} value={this.state.PlantEngineer} />
                  </td>
                </tr>
                <tr>
                  <td>RRD Engineer</td>
                  <td>
                    <input type="text" name="RRDEngineer" onChange={this.onChangeRRDEngineer} value={this.state.RRDEngineer}/>
                  </td>
                </tr>
                <tr>
                  <td>Network Engineer</td>
                  <td>
                    <input type="text" name="NetworkEngineer" onChange={this.onChangeNetworkEngineer} value={this.state.NetworkEngineer} />
                  </td>
                </tr>
                <tr>
                  <td>Operations Engineer</td>
                  <td>
                    <input type="text" name="OperationsEngineer" onChange={this.onChangeOperationsEngineer} value={this.state.OperationsEngineer} />
                  </td>
                </tr>
                <tr>
                  <td>Software Developer</td>
                  <td>
                    <input type="text" name="SoftwareDeveloper" onChange={this.onChangeSoftwareDeveloper} value={this.state.SoftwareDeveloper} />
                  </td>
                </tr>
                <tr>
                  <td>Software Engineer</td>
                  <td>
                    <input type="text" name="SoftwareEngineer" onChange={this.onChangeSoftwareEngineer} value={this.state.SoftwareEngineer} />
                  </td>
                </tr>
                <tr>
                  <td>Software Tester</td>
                  <td>
                    <input type="text" name="SoftwareTester" onChange={this.onChangeSoftwareTester} value={this.state.SoftwareTester} />
                  </td>
                </tr>
              </Table>
            </Modal.Body>
            <Modal.Footer>
              <Button type="submit" >Submit</Button>
            </Modal.Footer>
            </form>
          </Modal>
        </Card>
      </div>
    );
  }
Example #25
Source File: CurrentJob.js    From GB-GCGC with MIT License 4 votes vote down vote up
render(){
  return (
    <div className="CurrentJob">
      <Card className="Rounded p-3">
        <CardSubtitle align="left">Current Job Suitability</CardSubtitle>
        <hr></hr>
        <div className="container">
          <Row>
            <Col lg="4" md="6" sm="12">
                      <Doughnut data={{datasets: [{
                                data: [this.state.Analyst,100-this.state.Analyst],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      />Analyst
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state.CustomerSales,100-this.state.CustomerSales],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      />CustomerSales
            </Col>
            <Col lg="4" md="6" sm="12">
              <Doughnut data={{datasets: [{
                                data: [this.state.PlantEngineer,100-this.state.PlantEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Plant Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
              <Doughnut data={{datasets: [{
                                data: [this.state. RRDEngineer,100-this.state. RRDEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      />RRD Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state.NetworkEngineer,100-this.state.NetworkEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Network Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state. OperationsEngineer,100-this.state.OperationsEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Operations Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state.SoftwareDeveloper,100-this.state.SoftwareDeveloper],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Software Developer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state. SoftwareEngineer,100-this.state. SoftwareEngineer],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      /> Software Engineer
            </Col>
            <Col lg="4" md="6" sm="12">
            <Doughnut data={{datasets: [{
                                data: [this.state. SoftwareTester,100-this.state.SoftwareTester],
                                backgroundColor: ['#4169E1','#EEEEEE'],
                                 hoverBackgroundColor: ['#4169E1','#EEEEEE']
                           }]}} 
                      />Software Tester
            </Col>
          </Row>
        </div>
        <br />
       <br />
      </Card>
    </div>
  );
}
Example #26
Source File: index.js    From covidzero-frontend with Apache License 2.0 4 votes vote down vote up
RegionCases = (props) => {
    const [responseAPI, setResponseAPI] = useState([]);

    const [lastDay, setLastDay] = useState(null);

    const [sul, setSul] = useState([]);
    const [sudeste, setSudeste] = useState([]);
    const [centroOeste, setCentroOeste] = useState([]);
    const [nordeste, setNordeste] = useState([]);
    const [norte, setNorte] = useState([]);

    const [graphic, setGraphic] = useState(null);

    useEffect(() => {
        getRegionCases();
    }, [getRegionCases]);

    useEffect(() => {

        if(!lastDay){
            return
        }

        const sulValue = responseAPI.reduce((currentTotal, item) => {

            if(item.date == lastDay && item.region == 'Sul' && item.codmun == null){
                return currentTotal + item.totalCases
            }
            return currentTotal;
        }, 0);

        const sudesteValue = responseAPI.reduce((currentTotal, item) => {
            if(item.date == lastDay && item.region == 'Sudeste' && item.codmun == null){
                return currentTotal + item.totalCases
            }
            return currentTotal;
        }, 0);

        const centroOesteValue = responseAPI.reduce((currentTotal, item) => {
            if(item.date == lastDay && item.region === 'Centro-Oeste' && item.codmun == null){
                return currentTotal + item.totalCases;
            }
            return currentTotal;
        }, 0);

        const nordesteValue = responseAPI.reduce((currentTotal, item) => {
            if(item.date == lastDay && item.region == 'Nordeste' && item.codmun == null){
                return currentTotal + item.totalCases
            }
            return currentTotal;
        }, 0);

        const norteValue = responseAPI.reduce((currentTotal, item) => {
            if(item.date == lastDay && item.region == 'Norte' && item.codmun == null){
                return currentTotal + item.totalCases
            }
            return currentTotal;
        }, 0);

        setSul(sulValue);
        setSudeste(sudesteValue);
        setCentroOeste(centroOesteValue);
        setNordeste(nordesteValue);
        setNorte(norteValue);

    }, [lastDay, responseAPI]);

    useEffect(() => {

        setGraphic(
            {
                labels: ['Sul', 'Sudeste', 'Centro-oeste', 'Nordeste', 'Norte'],
                datasets: [
                {
                    backgroundColor: [
                        '#EF9350',
                        '#50EFC9',
                        '#6650EF',
                        '#CC00FF',
                        '#61DD27',
                        ],
                    borderWidth: 0.6,
                    data: [sul, sudeste, centroOeste, nordeste, norte],

                }
                ],
            }
        );
    }, [sul, sudeste, centroOeste, nordeste, norte]);

    async function getRegionCases(){
        const response = await regionCasesService.get().then(response => {
            return response.data;
        });

        setResponseAPI(response);

        const lastDay = response[1].date;

        setLastDay(lastDay);
    };

    return(
        <Style.CardBoxStyle>
            <Style.Title>{props.title}</Style.Title>
            <Style.CardBoxStatsDefault>
                { graphic && <Doughnut
                    data={graphic}
                    options={{
                    cutoutPercentage: 80,

                        legend:{
                            display: true,
                            labels: {
                                fontFamily: 'Ubuntu',
                                fontColor: 'white',
                                boxWidth: 8,
                                fontSize: 11,
                                padding: 4,
                            },
                            borderWidth: 0,
                            position: 'right',
                        },
                    }}
                /> }

            </Style.CardBoxStatsDefault>
        </Style.CardBoxStyle>
    );

}
Example #27
Source File: LabelsChart.js    From pomodor with MIT License 4 votes vote down vote up
LabelsChart = () => {
  const labels = useSelector((state) => state.labels.data)
  const sessions = useSelector((state) => state.sessions)
  const darkMode = useSelector((state) => +state.settings.darkMode)
  const darkModeCached = +localStorage.getItem('darkMode')

  const firstDayOfTheWeek = useSelector(
    (state) => state.settings.firstDayOfTheWeek
  )

  const [chartData, setChartData] = useState({
    labels: [],
    datasets: [{ data: [], backgroundColor: [] }],
  })

  const theme = useTheme()

  const [chartOptions, setChartOptions] = useState({
    maintainAspectRatio: false,
    legend: {
      labels: {
        fontColor: theme.palette.text.secondary,
        boxWidth: 20,
      },
    },
    tooltips: {
      callbacks: {
        title: generateChartTitle,
        label: generateChartTimeLabel,
      },
    },
  })

  const [calculatedData, setCalculatedData] = useState()
  const [dataType, setDataType] = useState('time')
  const [anchorEl, setAnchorEl] = useState(null)
  const [filter, setFilter] = useState(filters.find((f) => f.default))

  useEffect(() => {
    setChartOptions((prev) => {
      const newData = { ...prev }
      newData.legend.labels.fontColor = theme.palette.text.secondary
      return newData
    })

    setChartData((prev) => {
      const newData = { ...prev }

      newData.datasets[0].backgroundColor = [
        ...newData.datasets[0].backgroundColor,
      ]

      return newData
    })
  }, [darkModeCached, theme.palette.text.secondary])

  useEffect(() => {
    if (sessions && sessions.length && firstDayOfTheWeek) {
      if (firstDayOfTheWeek === 'Monday') {
        dayjs.locale('en-gb')
      } else {
        dayjs.locale('en')
      }

      const labelsData = labels.map((label) => {
        return {
          ...label,
          sessions: 0,
          time: 0,
        }
      })

      labelsData.push({
        id: null,
        color: 'grey',
        name: 'Unlabeled',
        sessions: 0,
        time: 0,
      })

      const filterFn = getFilterFn(filter)

      sessions.forEach(({ createdAt, duration, label }) => {
        if (filterFn(createdAt, dayjs)) {
          const index = labelsData.findIndex((l) => l.id === label)

          if (index < 0) return

          labelsData[index] = {
            ...labelsData[index],
            sessions: labelsData[index].sessions + 1,
            time: labelsData[index].time + getSeconds(duration),
          }
        }
      })

      setCalculatedData(labelsData)

      setChartData((prev) => {
        const newData = { ...prev }
        newData.datasets[0].data = labelsData.map((d) => d[dataType])
        newData.datasets[0].backgroundColor = labelsData.map((l) =>
          darkModeCached
            ? materialColors[l.color][200]
            : materialColors[l.color][500]
        )
        newData.labels = labelsData.map((l) => l.name)

        return newData
      })
    }
  }, [sessions, firstDayOfTheWeek, filter, dataType, labels, darkModeCached])

  const onChipClicked = (typeSelected) => {
    if (typeSelected === dataType) return

    setDataType(typeSelected)

    setChartData((prev) => {
      const newData = { ...prev }
      newData.datasets[0].data = calculatedData.map(
        (data) => data[typeSelected]
      )
      return newData
    })

    setChartOptions((prev) => {
      const newOptions = { ...prev }

      newOptions.tooltips.callbacks.label =
        typeSelected === 'time'
          ? generateChartTimeLabel
          : generateChartSessionsLabel

      return newOptions
    })
  }

  const openMenu = (event) => {
    setAnchorEl(event.currentTarget)
  }

  const closeMenu = () => {
    setAnchorEl(null)
  }

  const handleSelect = (filter) => {
    setFilter(filter)
    closeMenu()
  }
  const getSeconds = ({ minutes, seconds }) => minutes * 60 + seconds

  return (
    <Card theme={theme} dark={darkMode}>
      <CardHeader
        title="Labels"
        action={
          <IconButton aria-label="filtering options" onClick={openMenu}>
            <MoreVertIcon />
          </IconButton>
        }
      ></CardHeader>

      <Menu
        id="long-menu"
        anchorEl={anchorEl}
        open={!!anchorEl}
        onClose={closeMenu}
        margin="dense"
      >
        {filters.map((f, i) => (
          <MenuItem
            selected={filter.value === f.value}
            key={i}
            onClick={() => handleSelect(f)}
          >
            {f.name}
          </MenuItem>
        ))}
      </Menu>

      <CardContent>
        <Typography color="textSecondary">
          {filter.displayName || filter.name || ''}
        </Typography>

        <ChartContainer>
          <Doughnut data={chartData} options={chartOptions} />
        </ChartContainer>
      </CardContent>

      <CardActions>
        <div>
          <Box mr={1} display="inline-block">
            <Chip
              onClick={() => onChipClicked('time')}
              label="Time"
              color={dataType === 'time' ? 'primary' : 'default'}
              clickable
            />
          </Box>

          <Chip
            onClick={() => onChipClicked('sessions')}
            label="Sessions"
            color={dataType === 'sessions' ? 'primary' : 'default'}
            clickable
          />
        </div>
      </CardActions>
    </Card>
  )
}
Example #28
Source File: DaysChart.js    From pomodor with MIT License 4 votes vote down vote up
DaysChart = () => {
  const sessions = useSelector((state) => state.sessions)
  const darkMode = useSelector((state) => +state.settings.darkMode)
  const darkModeCached = +localStorage.getItem('darkMode')

  const firstDayOfTheWeek = useSelector(
    (state) => state.settings.firstDayOfTheWeek
  )

  const [chartData, setChartData] = useState({
    labels: daysOfWeek,
    datasets: [
      {
        data: Array(7).fill(1),
        backgroundColor: [],
      },
    ],
  })

  const theme = useTheme()

  const [chartOptions, setChartOptions] = useState({
    maintainAspectRatio: false,
    legend: {
      labels: {
        fontColor: theme.palette.text.secondary,
        boxWidth: 20,
      },
    },
    tooltips: {
      callbacks: {
        title: generateChartTitle,
        label: generateChartTimeLabel,
      },
    },
  })

  const [calculatedData, setCalculatedData] = useState()
  const [dataType, setDataType] = useState('time')
  const [anchorEl, setAnchorEl] = useState(null)
  const [filter, setFilter] = useState(filters.find((f) => f.default))

  useEffect(() => {
    if (sessions && sessions.length && firstDayOfTheWeek) {
      let week = [...daysOfWeek]

      if (firstDayOfTheWeek === 'Monday') {
        dayjs.locale('en-gb')
      } else {
        dayjs.locale('en')
      }

      const filterFn = getFilterFn(filter)

      const data = Array(7)
        .fill()
        .map(() => ({ sessions: 0, time: 0 }))

      sessions.forEach(({ createdAt, duration }) => {
        if (filterFn(createdAt, dayjs)) {
          const dayIndex = dayjs(createdAt).day()

          data[dayIndex] = {
            sessions: data[dayIndex].sessions + 1,
            time: data[dayIndex].time + getSeconds(duration),
          }
        }
      })

      if (firstDayOfTheWeek === 'Monday') {
        const sunday = data[0]
        data.splice(0, 1)
        data.push(sunday)

        week.splice(0, 1)
        week.push('Sunday')
      }

      setCalculatedData(data)

      setChartData((prev) => {
        const newData = { ...prev }
        newData.datasets[0].data = data.map((d) => d[dataType])

        newData.labels = week
        return newData
      })
    }
  }, [sessions, firstDayOfTheWeek, filter, dataType])

  const onChipClicked = (typeSelected) => {
    if (typeSelected === dataType) return

    setDataType(typeSelected)

    setChartData((prev) => {
      const newData = { ...prev }
      newData.datasets[0].data = calculatedData.map(
        (data) => data[typeSelected]
      )
      return newData
    })

    setChartOptions((prev) => {
      const newOptions = { ...prev }

      newOptions.tooltips.callbacks.label =
        typeSelected === 'time'
          ? generateChartTimeLabel
          : generateChartSessionsLabel

      return newOptions
    })
  }

  useEffect(() => {
    setChartOptions((prev) => {
      const newData = { ...prev }
      newData.legend.labels.fontColor = theme.palette.text.secondary
      return newData
    })

    setChartData((prev) => {
      const newData = { ...prev }
      newData.datasets[0].backgroundColor = colors.map((c) =>
        darkModeCached ? c.darkMode : c.normal
      )
      return newData
    })
  }, [darkModeCached, theme.palette.text.secondary])

  const openMenu = (event) => {
    setAnchorEl(event.currentTarget)
  }

  const closeMenu = () => {
    setAnchorEl(null)
  }

  const handleSelect = (filter) => {
    setFilter(filter)
    closeMenu()
  }

  const getSeconds = ({ minutes, seconds }) => minutes * 60 + seconds

  return (
    <Card theme={theme} dark={darkMode}>
      <CardHeader
        title="Days of week"
        action={
          <IconButton aria-label="filtering options" onClick={openMenu}>
            <MoreVertIcon />
          </IconButton>
        }
      ></CardHeader>

      <Menu
        id="long-menu"
        anchorEl={anchorEl}
        open={!!anchorEl}
        onClose={closeMenu}
        margin="dense"
      >
        {filters.map((f, i) => (
          <MenuItem
            selected={filter.value === f.value}
            key={i}
            onClick={() => handleSelect(f)}
          >
            {f.name}
          </MenuItem>
        ))}
      </Menu>

      <CardContent>
        <Typography color="textSecondary">
          {filter.displayName || filter.name || ''}
        </Typography>

        <ChartContainer>
          <Doughnut data={chartData} options={chartOptions} />
        </ChartContainer>
      </CardContent>

      <CardActions>
        <div>
          <Box mr={1} display="inline-block">
            <Chip
              onClick={() => onChipClicked('time')}
              label="Time"
              color={dataType === 'time' ? 'primary' : 'default'}
              clickable
            />
          </Box>

          <Chip
            onClick={() => onChipClicked('sessions')}
            label="Sessions"
            color={dataType === 'sessions' ? 'primary' : 'default'}
            clickable
          />
        </div>
      </CardActions>
    </Card>
  )
}
Example #29
Source File: Charts.js    From id.co.moonlay-eworkplace-admin-web with MIT License 4 votes vote down vote up
render() {
    return (
      <div className="animated fadeIn">
        <CardColumns className="cols-2">
          <Card>
            <CardHeader>
              Line Chart
              <div className="card-header-actions">
                <a href="http://www.chartjs.org" className="card-header-action">
                  <small className="text-muted">docs</small>
                </a>
              </div>
            </CardHeader>
            <CardBody>
              <div className="chart-wrapper">
                <Line data={line} options={options} />
              </div>
            </CardBody>
          </Card>
          <Card>
            <CardHeader>
              Bar Chart
              <div className="card-header-actions">
                <a href="http://www.chartjs.org" className="card-header-action">
                  <small className="text-muted">docs</small>
                </a>
              </div>
            </CardHeader>
            <CardBody>
              <div className="chart-wrapper">
                <Bar data={bar} options={options} />
              </div>
            </CardBody>
          </Card>
          <Card>
            <CardHeader>
              Doughnut Chart
              <div className="card-header-actions">
                <a href="http://www.chartjs.org" className="card-header-action">
                  <small className="text-muted">docs</small>
                </a>
              </div>
            </CardHeader>
            <CardBody>
              <div className="chart-wrapper">
                <Doughnut data={doughnut} />
              </div>
            </CardBody>
          </Card>
          <Card>
            <CardHeader>
              Radar Chart
              <div className="card-header-actions">
                <a href="http://www.chartjs.org" className="card-header-action">
                  <small className="text-muted">docs</small>
                </a>
              </div>
            </CardHeader>
            <CardBody>
              <div className="chart-wrapper">
                <Radar data={radar} />
              </div>
            </CardBody>
          </Card>
          <Card>
            <CardHeader>
              Pie Chart
              <div className="card-header-actions">
                <a href="http://www.chartjs.org" className="card-header-action">
                  <small className="text-muted">docs</small>
                </a>
              </div>
            </CardHeader>
            <CardBody>
              <div className="chart-wrapper">
                <Pie data={pie} />
              </div>
            </CardBody>
          </Card>
          <Card>
            <CardHeader>
              Polar Area Chart
              <div className="card-header-actions">
                <a href="http://www.chartjs.org" className="card-header-action">
                  <small className="text-muted">docs</small>
                </a>
              </div>
            </CardHeader>
            <CardBody>
              <div className="chart-wrapper">
                <Polar data={polar} options={options}/>
              </div>
            </CardBody>
          </Card>
        </CardColumns>
      </div>
    );
  }