Get started
Introduction
Installation
Your first app
Tutorials
Fission tutorials
Build a responsive solar energy dashboard in Rust
Core concepts
Components
State and effects
Protected routes
Server-side rendering
Styling
Testing
Deployment
Reference
API reference
Cookbook
Fission 0.16.0
Documentation version
Read the changelog →

Build a responsive solar energy dashboard in Rust

Import solar readings, compare actual energy with its matching forecast and keep missing telemetry explicit as the dashboard moves between phone and tablet layouts.
Android

What you will build

Review real site/day readings over seven or thirty days without confusing missing telemetry with zero generation or changing the range during a resize.
Validate one report before replacing its prior data
Compare actual generation and forecast over the same reported subset
Show unavailable percentages and forecast still awaiting readings
Keep one retained range above independently constructed responsive branches

Compare the same observations

A solar fleet operator needs to distinguish low production from missing telemetry. Treating a missing reading as zero creates a convincing chart of a result that was never measured. Comparing reported generation with the forecast for a larger, unmatched fleet is misleading for a different reason.
This dashboard imports a report containing site/day readings and forecasts. It compares actual energy with the forecast for those same reported rows, while separately showing forecast energy awaiting telemetry. Below-forecast output is a reason to review the source and conditions, not proof that an inverter has failed.

Create a shared mobile app

Complete Android SDK/NDK setup and iOS development setup for the platforms you intend to run. Android can use an emulator or a phone; iOS commands require macOS and Xcode.
cargo install cargo-fission
fission init cedar-peak-solar
cd cedar-peak-solar
fission add-target android --project-dir .
fission add-target ios --project-dir .
cargo add [email protected] --features charts
cargo add serde_yaml
Keep the generated main entrypoint. Shared state, parsing, components and translations run unchanged in Android, iOS and Web. There is no browser-only dataset and no implicit connection to a telemetry service.

Run the finished example

fission run --target android --project-dir .

1. Preserve missing data as a separate fact

The input uses five tab-separated columns without a header:
days_ago    site_id    site_name    generated_kwh    forecast_kwh
Use actual tab separators, whole kWh counts, and the literal machine value missing when an expected generation reading was not supplied. An actual measured zero is 0; those values must not become interchangeable. The parser rejects duplicates, inconsistent names for one site ID, invalid counts and oversized input before replacing the current report.
Day 0 is the supplied reporting endpoint. The seven-day window covers offsets 0–6 and thirty days covers 0–29. Every row must refer to the same endpoint and compatible energy interval. A label does not perform calendar arithmetic or verify the source's forecast method.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/state.rs","value":"src-state-rs"},{"index":1,"label":"src/import_form.rs","value":"src-import-form-rs"},{"index":2,"label":"src/site_row.rs","value":"src-site-row-rs"},{"index":3,"label":"src/summary.rs","value":"src-summary-rs"},{"index":4,"label":"src/app.rs","value":"src-app-rs"},{"index":5,"label":"src/translations.rs","value":"src-translations-rs"},{"index":6,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":7,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"},{"index":8,"label":"src/lib.rs","value":"src-lib-rs"},{"index":9,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/state.rs","value":"src-state-rs"}
use std::collections::{BTreeMap, BTreeSet};
use fission::prelude::*;

#[derive(Debug, Clone)]
pub struct SolarReading {
    pub days_ago: u8,
    pub site_id: String,
    pub site_name: String,
    pub generated_kwh: Option<u32>,
    pub forecast_kwh: u32,
}
#[derive(Debug, Clone)]
pub struct SolarReport { pub endpoint: String, pub rows: Vec<SolarReading> }
#[derive(Debug, Default)]
pub struct SolarDashboardState {
    pub report: Option<SolarReport>,
    pub import_issue: Option<&'static str>,
}
impl GlobalState for SolarDashboardState {}

pub fn parse_report(endpoint: &str, raw: &str) -> Result<SolarReport, &'static str> {
    if endpoint.trim().is_empty() || endpoint.chars().count() > 80 || raw.len() > 256 * 1024 {
        return Err("solar.invalid");
    }
    let mut rows = Vec::new();
    let mut seen = BTreeSet::new();
    let mut names: BTreeMap<String, String> = BTreeMap::new();
    for line in raw.lines().filter(|line| !line.trim().is_empty()) {
        let fields: Vec<&str> = line.split('\t').collect();
        if fields.len() != 5 || rows.len() >= 1_500 { return Err("solar.invalid"); }
        let days_ago: u8 = fields[0].trim().parse().map_err(|_| "solar.invalid")?;
        let site_id = fields[1].trim();
        let site_name = fields[2].trim();
        let generated_kwh = match fields[3].trim() {
            "missing" => None,
            text => Some(text.parse::<u32>().map_err(|_| "solar.invalid")?),
        };
        let forecast_kwh: u32 = fields[4].trim().parse().map_err(|_| "solar.invalid")?;
        if days_ago >= 30 || site_id.is_empty() || site_id.len() > 64
            || !site_id.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')
            || site_name.is_empty() || site_name.chars().count() > 80
            || generated_kwh.is_some_and(|value| value > 1_000_000_000)
            || forecast_kwh > 1_000_000_000
            || !seen.insert((days_ago, site_id.to_owned())) {
            return Err("solar.invalid");
        }
        if names.get(site_id).is_some_and(|name| name != site_name) { return Err("solar.invalid"); }
        names.insert(site_id.to_owned(), site_name.to_owned());
        rows.push(SolarReading {
            days_ago, site_id: site_id.to_owned(), site_name: site_name.to_owned(),
            generated_kwh, forecast_kwh,
        });
    }
    if rows.is_empty() { return Err("solar.empty_import"); }
    Ok(SolarReport { endpoint: endpoint.trim().to_owned(), rows })
}
impl SolarDashboardState {
    pub fn import(&mut self, endpoint: &str, raw: &str) {
        match parse_report(endpoint, raw) {
            Ok(report) => { self.report = Some(report); self.import_issue = None; }
            Err(key) => self.import_issue = Some(key),
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Totals {
    pub generated_kwh: u64,
    pub matched_forecast_kwh: u64,
    pub missing_forecast_kwh: u64,
    pub reported: usize,
    pub missing: usize,
}
impl Totals {
    pub fn percent(self) -> Option<f32> {
        (self.matched_forecast_kwh > 0)
            .then(|| self.generated_kwh as f64 / self.matched_forecast_kwh as f64 * 100.0)
            .map(|value| value as f32)
    }
    fn add(&mut self, row: &SolarReading) {
        if let Some(actual) = row.generated_kwh {
            self.generated_kwh += u64::from(actual);
            self.matched_forecast_kwh += u64::from(row.forecast_kwh);
            self.reported += 1;
        } else {
            self.missing_forecast_kwh += u64::from(row.forecast_kwh);
            self.missing += 1;
        }
    }
}
#[derive(Debug, Clone)]
pub struct SiteSummary { pub id: String, pub name: String, pub totals: Totals }
impl SolarReport {
    pub fn totals(&self, days: u8) -> Totals {
        let mut totals = Totals::default();
        for row in self.rows.iter().filter(|row| row.days_ago < days) { totals.add(row); }
        totals
    }
    pub fn daily(&self, days: u8) -> BTreeMap<u8, Totals> {
        let mut daily: BTreeMap<u8, Totals> = BTreeMap::new();
        for row in self.rows.iter().filter(|row| row.days_ago < days) {
            daily.entry(row.days_ago).or_default().add(row);
        }
        daily
    }
    pub fn chart_buckets(&self, days: u8) -> BTreeMap<u8, Totals> {
        let step = if days == 30 { 5 } else { 1 };
        let mut buckets: BTreeMap<u8, Totals> = BTreeMap::new();
        for row in self.rows.iter().filter(|row| row.days_ago < days) {
            buckets.entry(row.days_ago / step).or_default().add(row);
        }
        buckets
    }
    pub fn sites(&self, days: u8) -> Vec<SiteSummary> {
        let mut sites: BTreeMap<String, SiteSummary> = BTreeMap::new();
        for row in self.rows.iter().filter(|row| row.days_ago < days) {
            sites.entry(row.site_id.clone()).or_insert_with(|| SiteSummary {
                id: row.site_id.clone(), name: row.site_name.clone(), totals: Totals::default(),
            }).totals.add(row);
        }
        sites.into_values().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn missing_is_not_zero_and_forecast_uses_the_matching_subset() {
        let report = parse_report("Endpoint",
            "0\teast\tEast\t80\t100\n0\twest\tWest\tmissing\t900\n29\teast\tEast\t0\t50"
        ).unwrap();
        let week = report.totals(7);
        assert_eq!(week.percent(), Some(80.0));
        assert_eq!(week.missing_forecast_kwh, 900);
        assert_eq!((week.reported, week.missing), (1, 1));
        assert_eq!(report.totals(30).reported, 2);
        assert_eq!(report.chart_buckets(30).get(&5).unwrap().reported, 1);
        assert_eq!(Totals::default().percent(), None);
    }
    #[test]
    fn replacement_is_atomic_and_site_names_do_not_disagree() {
        let mut state = SolarDashboardState::default();
        state.import("Valid", "0\teast\tEast\t80\t100");
        state.import("Invalid", "0\teast\tEast\tNaN\t100");
        assert_eq!(state.report.as_ref().unwrap().endpoint, "Valid");
        assert!(parse_report("Conflicting labels",
            "0\teast\tEast\t80\t100\n1\teast\tWest\t90\t100"
        ).is_err());
    }
}

{"id":"fission-tabs-1","index":1,"label":"src/import_form.rs","value":"src-import-form-rs"}
use fission::prelude::*;
use crate::state::SolarDashboardState;

fission_component! {
    pub ImportSolarReport<SolarDashboardState> {
        state { endpoint: String = String::new(), source: String = String::new() }
    }
    view(form, state, cx) { let tokens = &cx.view.env().theme.tokens; } =>
    Column(gap: tokens.spacing.s, children: [
        Text(cx.tr("solar.import")).weight(tokens.typography.font_weight_bold),
        TextInput(label: Some(cx.tr("solar.endpoint").into()), bind: form.endpoint,
            semantics_identifier: "solar.endpoint".to_owned()),
        TextInput(label: Some(cx.tr("solar.tsv").into()), bind: form.source,
            multiline: true, helper_text: Some(cx.tr("solar.columns").into()),
            semantics_identifier: "solar.tsv".to_owned()),
        Button(
            child: Text(cx.tr("solar.replace")), key: "solar.import",
            on_press: reduce { state.import(&form.endpoint, &form.source); },
        ),
        if let Some(issue) = state.import_issue {
            Text(cx.tr(issue)).color(tokens.colors.error)
        },
    ])
}
{"id":"fission-tabs-1","index":2,"label":"src/site_row.rs","value":"src-site-row-rs"}
use fission::prelude::*;
use crate::state::SiteSummary;

fission_component! {
    pub SolarSiteStatus<()> { props { site: SiteSummary } }
    view(row, _state, cx) { let tokens = &cx.view.env().theme.tokens; } =>
    Container(
        Column(gap: tokens.spacing.s, children: [
            Text(row.site.name.clone()).weight(tokens.typography.font_weight_bold),
            if row.site.totals.missing > 0 {
                Text(format!("{}: {}", cx.tr("solar.missing_rows"), row.site.totals.missing))
            },
            if let Some(percent) = row.site.totals.percent() {
                Column(gap: tokens.spacing.xs, children: [
                    Text(format!("{}: {percent:.1}%", cx.tr("solar.matched_percent"))),
                    Text(cx.tr(if percent < 100.0 { "solar.review" } else { "solar.met_forecast" })),
                ])
            } else { Text(cx.tr("solar.no_ratio")) },
            if row.site.totals.reported > 0 {
                Column(gap: tokens.spacing.xs, children: [
                    Text(format!("{}: {:.3}", cx.tr("solar.generated"),
                        row.site.totals.generated_kwh as f64 / 1000.0)),
                    Text(format!("{}: {:.3}", cx.tr("solar.matched_forecast"),
                        row.site.totals.matched_forecast_kwh as f64 / 1000.0)),
                ])
            } else { Text(cx.tr("solar.no_generation")) },
        ])
    ).padding_all(tokens.spacing.m).bg(tokens.colors.surface)
        .border(tokens.colors.border, 1.0).border_radius(tokens.radii.medium)
}
{"id":"fission-tabs-1","index":3,"label":"src/summary.rs","value":"src-summary-rs"}
use fission::prelude::*;
use crate::{site_row::SolarSiteStatus, state::SolarDashboardState};

fission_component! {
    pub SolarFleetSummary<SolarDashboardState> { props { days: u8 } }
    view(summary, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let totals = state.report.as_ref().map(|report| report.totals(summary.days));
    } =>
    if let (Some(report), Some(totals)) = (&state.report, totals) {
        Column(gap: tokens.spacing.m, children: [
            Text(report.endpoint.clone()).weight(tokens.typography.font_weight_bold),
            if totals.reported > 0 {
                Column(gap: tokens.spacing.xs, children: [
                    Text(format!("{}: {:.3}", cx.tr("solar.generated"), totals.generated_kwh as f64 / 1000.0)),
                    Text(format!("{}: {:.3}", cx.tr("solar.matched_forecast"),
                        totals.matched_forecast_kwh as f64 / 1000.0)),
                ])
            } else { Text(cx.tr("solar.no_generation")) },
            Text(format!("{}: {:.3}", cx.tr("solar.missing_forecast"),
                totals.missing_forecast_kwh as f64 / 1000.0)),
            Text(format!("{}: {} / {}", cx.tr("solar.coverage"),
                totals.reported, totals.reported + totals.missing)),
            if let Some(percent) = totals.percent() {
                Text(format!("{}: {percent:.1}%", cx.tr("solar.matched_percent")))
            } else { Text(cx.tr("solar.no_ratio")) },
            Text(cx.tr("solar.sites")).weight(tokens.typography.font_weight_bold),
            Column(gap: tokens.spacing.s, children: [
                for site in report.sites(summary.days) {
                    SolarSiteStatus(site.clone(), key: site.id.clone())
                        .id(WidgetId::explicit(&format!("solar.site.{}", site.id)))
                },
            ]),
        ])
    } else { Text(cx.tr("solar.empty")) }
}
{"id":"fission-tabs-1","index":4,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::{import_form::ImportSolarReport, state::SolarDashboardState, summary::SolarFleetSummary};

fission_component! {
    pub SolarFleetDashboardPage<SolarDashboardState> {
        state { thirty_days: bool = false }
    }
    view(page, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let days: u8 = if page.thirty_days { 30 } else { 7 };
    } =>
    SafeArea(child: Scroll(child: Container(
        Column(gap: tokens.spacing.l, children: [
            Text(cx.tr("solar.title")).size(tokens.typography.heading2_size),
            Text(cx.tr("solar.scope")),
            ImportSolarReport(),
            Row(gap: tokens.spacing.s, wrap: ir_op::FlexWrap::Wrap, children: [
                Button(
                    child: Text(cx.tr("solar.seven")), key: "solar.seven",
                    variant: if page.thirty_days { ButtonVariant::Outline } else { ButtonVariant::Primary },
                    on_press: reduce { page.thirty_days = false; },
                ),
                Button(
                    child: Text(cx.tr("solar.thirty")), key: "solar.thirty",
                    variant: if page.thirty_days { ButtonVariant::Primary } else { ButtonVariant::Outline },
                    on_press: reduce { page.thirty_days = true; },
                ),
            ]),
            SolarFleetSummary(days),
        ])
    ).padding_all(tokens.spacing.l)))
}
{"id":"fission-tabs-1","index":5,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::prelude::*;

pub fn create_env() -> Env {
    let mut env = Env::default();
    env.locale = Locale::from("en-US");
    for (locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid checked-in translations");
        env.i18n.add_bundle(TranslationBundle { locale: Locale::from(locale), messages });
    }
    env
}
{"id":"fission-tabs-1","index":6,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
solar.title: "Solar fleet report"
solar.scope: "Compare an imported report with its own forecast. This screen has no live telemetry service, fault diagnosis or remote control. Data stays in this session."
solar.import: "Import or replace a report"
solar.endpoint: "Reporting endpoint or export label"
solar.tsv: "Tab-separated site/day energy"
solar.columns: "No header: days before endpoint (0–29), site ID, site name, whole generated kWh or missing, whole forecast kWh. Use one reporting endpoint."
solar.replace: "Validate and replace report"
solar.invalid: "Invalid report. Check five tab-separated fields, stable site names, unique site/day pairs, days 0–29 and bounded whole-kWh counts. The previous report is unchanged."
solar.empty_import: "Enter at least one report row."
solar.generated: "Reported generated energy (MWh)"
solar.matched_forecast: "Forecast for those same reported rows (MWh)"
solar.missing_forecast: "Forecast awaiting generation readings (MWh)"
solar.coverage: "Supplied site/day readings with actual energy"
solar.matched_percent: "Actual as a percentage of matching forecast"
solar.no_ratio: "Percentage unavailable: no matching generation data or the matching forecast is zero."
solar.no_generation: "No actual generation was supplied for this selected subset; it is not zero."
solar.sites: "Site review"
solar.missing_rows: "Supplied rows missing telemetry"
solar.review: "Below the matching forecast. Review the source readings and conditions before deciding whether to inspect."
solar.met_forecast: "Matching reported output meets or exceeds forecast; this is not a full site-health assessment."
solar.empty: "No report loaded. Import actual site/day readings above."
solar.chart: "Reported energy against matching forecast"
solar.days_before: "Day −{days}"
solar.mwh: "MWh"
solar.day_axis: "Days before report endpoint"
solar.no_chart: "No actual generation readings in this selected window."
solar.chart_scope: "Both bars use the same reported site/day subset. Missing telemetry is excluded from both series and remains visible in the written coverage."
solar.seven: "7-day window"
solar.thirty: "30-day window"
{"id":"fission-tabs-1","index":7,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
solar.title: "Informe de la flota solar"
solar.scope: "Compara un informe importado con su previsión. No hay telemetría en directo, diagnóstico de averías ni control remoto. Los datos solo duran esta sesión."
solar.import: "Importar o sustituir un informe"
solar.endpoint: "Fecha de referencia o etiqueta de exportación"
solar.tsv: "Energía por instalación y día, separada por tabulaciones"
solar.columns: "Sin cabecera: días anteriores (0–29), ID, nombre, kWh enteros generados o missing, y previsión en kWh enteros. Usa una única referencia."
solar.replace: "Validar y sustituir el informe"
solar.invalid: "Informe no válido. Comprueba cinco campos, nombres coherentes, pares únicos de ID/día, días 0–29 y recuentos enteros acotados. Se conserva el informe anterior."
solar.empty_import: "Introduce al menos una fila."
solar.generated: "Energía generada comunicada (MWh)"
solar.matched_forecast: "Previsión para las mismas filas comunicadas (MWh)"
solar.missing_forecast: "Previsión pendiente de lecturas de generación (MWh)"
solar.coverage: "Lecturas instalación/día con generación real"
solar.matched_percent: "Generación real como porcentaje de la previsión comparable"
solar.no_ratio: "Porcentaje no disponible: faltan lecturas comparables o su previsión es cero."
solar.no_generation: "No se aportó generación real para este subconjunto; no equivale a cero."
solar.sites: "Revisión por instalación"
solar.missing_rows: "Filas aportadas sin telemetría"
solar.review: "Por debajo de la previsión comparable. Revisa lecturas y condiciones antes de decidir una inspección."
solar.met_forecast: "La producción comunicada alcanza la previsión; no es una evaluación completa del estado."
solar.empty: "No hay informe. Importa lecturas reales por instalación y día."
solar.chart: "Energía comunicada y previsión comparable"
solar.days_before: "Día −{days}"
solar.mwh: "MWh"
solar.day_axis: "Días anteriores a la referencia"
solar.no_chart: "No hay lecturas reales de generación en este intervalo."
solar.chart_scope: "Ambas barras usan el mismo subconjunto instalación/día. La telemetría ausente se excluye de ambas series y queda visible en la cobertura."
solar.seven: "Intervalo de 7 días"
solar.thirty: "Intervalo de 30 días"
{"id":"fission-tabs-1","index":8,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
pub mod state;
mod import_form;
mod site_row;
mod summary;
mod translations;

use app::SolarFleetDashboardPage;
use state::SolarDashboardState;
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<SolarDashboardState, _>::new(SolarFleetDashboardPage::new())
        .with_env(translations::create_env())
        .run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<SolarDashboardState, SolarFleetDashboardPage> {
    let app = MobileApp::<SolarDashboardState, _>::new(SolarFleetDashboardPage::new())
        .with_env(translations::create_env());
    #[cfg(all(target_os = "android", debug_assertions))]
    let app = app.with_test_control_port(48761);
    app
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> { mobile_app().run() }

#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
    let _ = mobile_app().run_with_android_app(app_handle);
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<SolarDashboardState, _>::new(SolarFleetDashboardPage::new())
        .with_env(translations::create_env())
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":9,"label":"preview/lib.rs","value":"preview-lib-rs"}
include!("../src/lib.rs");
{"id":"fission-tabs-1"}
Import readings you can check against their source. A missing reading must increase the missing count, not reduce measured generation to zero. A zero matching forecast makes the percentage unavailable, not zero percent. The report remains unchanged if a replacement fails validation.
Show the app preview
Hide the app preview

2. Keep the range above the responsive branches

The chart and written summary need the same selected records at every width. The page therefore owns the range once, above Responsive. Both independently constructed branches receive that value as a prop. Placing a separate range state inside each branch would allow resizing to change the apparent selection.
The wide branch puts the chart and site review side by side. The compact branch stacks them in the same reading order. Both are constructed from normal components, not clones of one retained widget tree. The active design-system breakpoint chooses the branch; the chart takes its available layout width rather than a hand-calculated fraction of the whole device.
Seven days uses daily bars. Thirty days uses six five-day buckets, not four weeks with two days silently dropped. A label such as 29–25 names the offsets before the report endpoint. Both series sum exactly the same reported subset within each bucket, keeping the comparison meaningful and the phone's axis readable.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/analytics.rs","value":"src-analytics-rs"},{"index":1,"label":"src/layouts.rs","value":"src-layouts-rs"},{"index":2,"label":"src/app.rs","value":"src-app-rs"},{"index":3,"label":"src/lib.rs","value":"src-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/analytics.rs","value":"src-analytics-rs"}
use fission::prelude::*;
use fission::charts::{Axis, BarSeries, Chart, Legend, Series};
use crate::state::{SolarDashboardState, Totals};

fission_component! {
    pub SolarGenerationTrend<SolarDashboardState> { props { days: u8 } }
    view(trend, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let daily: Vec<(u8, Totals)> = state.report.as_ref().map(|report| {
            report.chart_buckets(trend.days).into_iter().rev()
                .filter(|(_, totals)| totals.reported > 0).collect::<Vec<(u8, Totals)>>()
        }).unwrap_or_default();
        let labels: Vec<String> = daily.iter().map(|(bucket, _)| {
            if trend.days == 30 {
                format!("{}–{}", bucket * 5 + 4, bucket * 5)
            } else {
                cx.tr("solar.days_before").replace("{days}", &bucket.to_string())
            }
        }).collect();
        let actual: Vec<f32> = daily.iter().map(|(_, totals)| totals.generated_kwh as f32 / 1000.0).collect();
        let forecast: Vec<f32> = daily.iter().map(|(_, totals)| {
            totals.matched_forecast_kwh as f32 / 1000.0
        }).collect();
        let actual_label = cx.tr("solar.generated");
        let forecast_label = cx.tr("solar.matched_forecast");
    } =>
    if daily.is_empty() { Text(cx.tr("solar.no_chart")) } else {
        SemanticsRegion(
            identifier: Some("solar.generation".to_owned()),
            label: Some(cx.tr("solar.chart")),
            child: Column(gap: tokens.spacing.m, children: [
                Chart(
                    title: Some(cx.tr("solar.chart")),
                    x_axis: Some(Axis::category(labels.iter().map(String::as_str).collect()).name(cx.tr("solar.day_axis"))),
                    y_axis: Some(Axis::value().min(0.0).name(cx.tr("solar.mwh"))),
                    legend: Some(Legend::top_right()),
                    height: Some(300.0),
                    series: vec![
                        Series::Bar(BarSeries::new(&actual_label).data(actual)),
                        Series::Bar(BarSeries::new(&forecast_label).data(forecast)),
                    ],
                ),
                Text(cx.tr("solar.chart_scope")),
            ]),
        )
    }
}
{"id":"fission-tabs-1","index":1,"label":"src/layouts.rs","value":"src-layouts-rs"}
use fission::prelude::*;
use crate::{analytics::SolarGenerationTrend, state::SolarDashboardState, summary::SolarFleetSummary};

fission_component! {
    pub SolarInsightsCompact<SolarDashboardState> { props { days: u8 } }
    view(layout, _state, cx) =>
    Column(gap: cx.view.env().theme.tokens.spacing.l, children: [
        SolarGenerationTrend(layout.days),
        SolarFleetSummary(layout.days),
    ])
}

fission_component! {
    pub SolarInsightsWide<SolarDashboardState> { props { days: u8 } }
    view(layout, _state, cx) =>
    Row(gap: cx.view.env().theme.tokens.spacing.l, align_items: ir_op::AlignItems::Start, children: [
        Container(child: SolarGenerationTrend(layout.days))
            .width(0.0).min_width(0.0).flex_grow(1.0),
        Container(child: SolarFleetSummary(layout.days))
            .width(0.0).min_width(0.0).flex_grow(1.0),
    ])
}

{"id":"fission-tabs-1","index":2,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::{import_form::ImportSolarReport, state::SolarDashboardState, layouts::{SolarInsightsCompact, SolarInsightsWide}};

fission_component! {
    pub SolarFleetDashboardPage<SolarDashboardState> {
        state { thirty_days: bool = false }
    }
    view(page, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let days: u8 = if page.thirty_days { 30 } else { 7 };
        let layout = Responsive::new_with_id(
            WidgetId::explicit("solar.insights"),
            move || SolarInsightsWide { days },
        ).case_max_width_with(
            tokens.breakpoints.medium_max,
            move || SolarInsightsCompact { days },
        );
    } =>
    SafeArea(child: Scroll(child: Container(
        Column(gap: tokens.spacing.l, children: [
            Text(cx.tr("solar.title")).size(tokens.typography.heading2_size),
            Text(cx.tr("solar.scope")),
            ImportSolarReport(),
            Row(gap: tokens.spacing.s, wrap: ir_op::FlexWrap::Wrap, children: [
                Button(
                    child: Text(cx.tr("solar.seven")), key: "solar.seven",
                    variant: if page.thirty_days { ButtonVariant::Outline } else { ButtonVariant::Primary },
                    on_press: reduce { page.thirty_days = false; },
                ),
                Button(
                    child: Text(cx.tr("solar.thirty")), key: "solar.thirty",
                    variant: if page.thirty_days { ButtonVariant::Primary } else { ButtonVariant::Outline },
                    on_press: reduce { page.thirty_days = true; },
                ),
            ]),
            layout,
        ])
    ).padding_all(tokens.spacing.l)))
}
{"id":"fission-tabs-1","index":3,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
pub mod state;
mod import_form;
mod site_row;
mod summary;
mod analytics;
mod layouts;
mod translations;

use app::SolarFleetDashboardPage;
use state::SolarDashboardState;
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<SolarDashboardState, _>::new(SolarFleetDashboardPage::new())
        .with_env(translations::create_env())
        .run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<SolarDashboardState, SolarFleetDashboardPage> {
    let app = MobileApp::<SolarDashboardState, _>::new(SolarFleetDashboardPage::new())
        .with_env(translations::create_env());
    #[cfg(all(target_os = "android", debug_assertions))]
    let app = app.with_test_control_port(48761);
    app
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> { mobile_app().run() }

#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
    let _ = mobile_app().run_with_android_app(app_handle);
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<SolarDashboardState, _>::new(SolarFleetDashboardPage::new())
        .with_env(translations::create_env())
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
Select thirty days and resize between phone and tablet widths. The selected range, matched totals and missing-telemetry count must not change merely because the layout changed. Both bars use the same site/day subset; the missing forecast remains visible in text.
Show the app preview
Hide the app preview

3. Check units, coverage and layout together

cargo test
fission doctor android --project-dir .
fission run --target android --project-dir .
fission test --target android --project-dir .
fission build --target android --project-dir . --release
On macOS, run the same shared app through the iOS host:
fission doctor ios --project-dir .
fission run --target ios --project-dir .
fission test --target ios --project-dir .
fission build --target ios --project-dir . --release
The tests establish the distinction between missing and zero, matched-denominator arithmetic, offset 29 and preserving the previous report. They do not establish that the export covers every site or that a low value identifies a fault. Entirely omitted site/day rows are unknown to this app; a complete fleet coverage check would need an expected reporting schedule.
On each target, inspect an iPhone-sized view and a wider tablet view, increased text size, long site names and the soft keyboard. Confirm the chart and last site remain reachable by scrolling. Compare the written MWh totals with the source kWh values; the conversion is 1,000 kWh per MWh. Do not rely on colour alone to explain a site's status.
The source has no continuously updated clock, so the UI makes no claim about how many minutes ago telemetry arrived. Data remains in memory for this session. A live integration would introduce explicit effects, pending/error states and an identified reporting endpoint; it should not start work whilst constructing either responsive branch.
The responsive widget reference, Charts reference and state guide cover the mechanisms used here. Host startup is not visual, accessibility or device qualification.