日本語

Donut chart

A ring of arcs, each as long as one row's share of the total.

Result

donut_chart.rs
use hypersig::html::div;
use hypersig::style::pattern::stack;
use hypersig::style::value::rem;
use hypersig::{Page, Signals};
use hypersig_ui::{ButtonSize, ButtonVariant, DonutChart, button};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Browser {
    name: String,
    visitors: i32,
}

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Traffic {
    browsers: Vec<Browser>,
}

pub(super) fn page() -> Page<Traffic> {
    let browsers = ["Chrome", "Safari", "Firefox", "Edge"]
        .into_iter()
        .map(str::to_owned)
        .chain(["Other"
            .to_owned()])
        .zip([275, 200, 187, 173, 90])
        .map(|(name, visitors)| Browser { name, visitors })
        .collect();
    let grow = Traffic::browsers().update_where(
        |browser| browser.index().equals(2),
        Browser::visitors(),
        |browser| browser.at(Browser::visitors()) + 100,
    );
    Page::new(
        "Browsers",
        Traffic { browsers },
    )
    .child(
        div()
            .css(stack(rem(1)).max_width(rem(20)))
            .child(
                div().child(
                    button(ButtonVariant::Outline, ButtonSize::Sm)
                        .on_click(grow)
                        .text("Add 100 Firefox visitors"),
                ),
            )
            .child(
                DonutChart::new(
                    "Visitors by browser",
                    Traffic::browsers(),
                    Browser::name(),
                    Browser::visitors(),
                ),
            ),
    )
}

Accessibility

The chart is a <figure> named by its label. The ring, the total in its middle, and the legend are hidden from assistive technology, and a screen reader reads a visually hidden <table> instead: captioned with the label, one row per slice with its category as the row header and its value in the cell. The chart takes no keys.

Building a donut chart

DonutChart::new takes the chart's name, the list signal of its rows, the text field that labels each slice, and the number field that sizes it:

impl<S: 'static, T: 'static> DonutChart<S, T> {
    pub fn new<U: Number + Textual + 'static, R: FromPage>(
        label: impl Into<String>,
        rows: Sig<S, Vec<T>, R>,
        category: Sig<T, String>,
        value: Sig<T, U>,
    ) -> Self;
    pub fn format(self, format: NumberFormat) -> Self;
    pub fn render(self) -> El<S>;
}

Each row is an arc as long as its value over the sum of the values. The arcs run clockwise from the top in the order of the rows, in the colors token::chart_1 to token::chart_5, which repeat from the first after the fifth row. The total is written in the middle of the ring, and the legend names each row with its value. format writes the values and the total in a NumberFormat. A statement or a patch that changes a value resizes every arc and the total with no request. DonutChart converts into an El<S> and a Node<S>.

value must be a number field of the row type, so a text field is E0277:

use hypersig::Signals;
use hypersig_ui::DonutChart;
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Plan {
    name: String,
    revenue: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Revenue {
    plans: Vec<Plan>,
}

// error[E0277]: the browser does not do arithmetic on `String`
let chart = DonutChart::new("Revenue by plan", Revenue::plans(), Plan::name(), Plan::revenue());

The HTML

A chart of 275 Chrome visitors and 125 Safari visitors renders as:

<figure aria-label="Browsers">
  <div aria-hidden="true">
    <svg viewBox="0 0 100 100" width="100%" height="100%">
      <circle cx="50" cy="50" r="40" fill="none" stroke-width="16"></circle>
      <circle cx="50" cy="50" r="40" fill="none" stroke-width="16" pathLength="100" stroke-dasharray="68.750 31.250" stroke-dashoffset="0.000"></circle>
      <circle cx="50" cy="50" r="40" fill="none" stroke-width="16" pathLength="100" stroke-dasharray="31.250 68.750" stroke-dashoffset="-68.750"></circle>
    </svg>
    <div><span>400</span></div>
  </div>
  <ul aria-hidden="true">
    <li><span></span><span>Chrome</span><span>275</span></li>
    <li><span></span><span>Safari</span><span>125</span></li>
  </ul>
  <table>
    <caption>Browsers</caption>
    <thead><tr><th scope="col"></th><th scope="col">Browsers</th></tr></thead>
    <tbody>
      <tr><th scope="row">Chrome</th><td>275</td></tr>
      <tr><th scope="row">Safari</th><td>125</td></tr>
    </tbody>
  </table>
</figure>

The first <circle> is the ring behind the arcs, in token::muted. Each arc is a circle with pathLength="100", whose stroke-dasharray is the row's share of the total in hundredths and the rest, and whose stroke-dashoffset starts it where the rows before it end: 275 of 400 is 68.75 hundredths.

What is not checked

A negative value counts as 0, since a share cannot be negative: its row draws no arc and adds nothing to the total, while the legend and the table still show the negative value. With every value at 0, the ring draws no arcs and the total reads 0. After the fifth row the colors repeat, so the sixth slice has the first slice's color and only the legend's order tells them apart. Each arc sums the rows before it, so the work of a change grows with the square of the number of rows.

Example: revenue by plan

Three plans, with the values and the total written in dollars:

use hypersig::{NumberFormat, Page, Signals};
use hypersig_ui::DonutChart;
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Plan {
    name: String,
    revenue: f64,
}

#[derive(Signals, Serialize, Deserialize)]
struct Revenue {
    plans: Vec<Plan>,
}

const DOLLARS: NumberFormat = NumberFormat::new().prefix("$");

let chart = DonutChart::new("Revenue by plan", Revenue::plans(), Plan::name(), Plan::revenue())
    .format(DOLLARS);

let plans = vec![
    Plan { name: "Hobby".into(), revenue: 1200.0 },
    Plan { name: "Pro".into(), revenue: 5400.0 },
    Plan { name: "Team".into(), revenue: 3400.0 },
];
let html = Page::new("Revenue", Revenue { plans }).child(chart).render();

The Overlays pages come next, starting with Dialog.