import React from "react";
import {useSearchParams} from "react-router";
import {
Accordion,
Button,
Grid,
Group,
Header,
IconButton,
Loader,
Message,
NumberInput,
Panel,
Select,
Statistic,
StatisticGroup,
Table,
Tabs,
TextInput,
Toggle,
} from "../ui";
import {InfoPopup, roundDigits} from "../Common";
import {
DEFAULT_LOSSES,
defaultAzimuth,
estimateProduction,
formatMonthly,
INVERTER_NOMINAL_EFFICIENCY,
LOSS_CATEGORIES,
MODULE_TYPES,
MONTH_NAMES,
MOUNTINGS,
optimalTilt,
parseCoordinate,
parseMonthly,
totalLoss,
TRACKING,
} from "./solar";
import {
CLIMATOLOGY_ACKNOWLEDGMENT,
CLIMATOLOGY_CHANGES,
CLIMATOLOGY_DATA_REFERENCE,
CLIMATOLOGY_LICENSE,
lookupClimatology,
useClimatology,
} from "./solarData";
import {SolarOffGrid} from "./SolarOffGrid";
// Every input lives in the URL query so the Share button (which shares window.location.href) shares
// the whole configuration. Values equal to their default are left out to keep the URL, and its QR
// code, small. Keys are short and must stay stable; shared links depend on them.
const DEFAULT_PANEL_WATTS = 400;
const DEFAULT_PANEL_COUNT = 1;
const COMPASS = [
{value: '0', label: 'N'}, {value: '45', label: 'NE'}, {value: '90', label: 'E'}, {value: '135', label: 'SE'},
{value: '180', label: 'S'}, {value: '225', label: 'SW'}, {value: '270', label: 'W'}, {value: '315', label: 'NW'},
];
const fToC = f => (f - 32) * 5 / 9;
const cToF = c => c * 9 / 5 + 32;
const numberOr = (value, fallback) => {
if (value === null || value === undefined || value === '') {
return fallback;
}
const n = Number(value);
return Number.isFinite(n) ? n : fallback;
};
const fmt = (value, digits = 2) => (Number.isFinite(value) ? `${roundDigits(value, digits)}` : '—');
// Read and write the calculator's query parameters. Writes replace the history entry, so typing does
// not fill the Back button with one entry per keystroke.
export function useSolarParams() {
const [searchParams, setSearchParams] = useSearchParams();
const get = key => searchParams.get(key);
// `updates` maps keys to values; null, undefined and '' remove the key.
const set = updates => setSearchParams(prev => {
const next = new URLSearchParams(prev);
Object.entries(updates).forEach(([key, value]) => {
if (value === null || value === undefined || value === '') {
next.delete(key);
} else {
next.set(key, `${value}`);
}
});
return next;
}, {replace: true});
// Store a number, or remove it when it equals the default.
const setNumber = (key, value, fallback) =>
set({[key]: value === '' || Number(value) === fallback ? null : value});
return {searchParams, get, set, setNumber};
}
// Turn the query parameters into the model's inputs. Invalid values fall back to defaults, so a
// hand-edited or truncated link never crashes the page.
export function systemFromParams(get) {
const latitude = parseCoordinate(get('lat'), 'lat');
const longitude = parseCoordinate(get('lon'), 'lon');
const fahrenheit = get('tu') === 'f';
// Own sunlight data replaces the NASA data when present.
const ownData = get('ghi') !== null;
const ghi = parseMonthly(get('ghi')).map(v => (v !== null && v >= 0 ? v : null));
const temperatureInput = parseMonthly(get('temp'));
const temperature = temperatureInput.map(v => (v === null ? null : (fahrenheit ? fToC(v) : v)));
const panelWatts = Math.max(0, numberOr(get('pw'), DEFAULT_PANEL_WATTS));
const panelCount = Math.max(0, Math.round(numberOr(get('pn'), DEFAULT_PANEL_COUNT)));
const kwp = panelWatts * panelCount / 1000;
const tracking = TRACKING[get('track')] ? get('track') : 'fixed';
const mounting = MOUNTINGS[get('mount')] ? get('mount') : 'open';
const gamma = numberOr(get('gamma'), MODULE_TYPES.standard.gamma);
const defaultTilt = latitude === null ? 0 : Math.round(Math.abs(latitude));
const tilt = Math.min(90, Math.max(0, numberOr(get('tilt'), defaultTilt)));
const azimuth = numberOr(get('az'), defaultAzimuth(latitude ?? 0));
// Null means "use the monthly albedo from the data", which includes seasonal snow.
const albedoInput = numberOr(get('alb'), null);
const albedo = albedoInput === null ? null : Math.min(1, Math.max(0, albedoInput));
const lossValues = parseMonthly(get('losses'));
const losses = LOSS_CATEGORIES.map((c, i) => {
const v = lossValues[i];
return v !== null && v >= 0 && v <= 100 ? v : c.default;
});
const inverterOn = get('inv') === '1';
const acRating = numberOr(get('iac'), roundDigits(kwp / 1.2, 2));
const efficiency = numberOr(get('ieff'), INVERTER_NOMINAL_EFFICIENCY);
return {
latitude, longitude, fahrenheit, ownData, ghi, temperatureInput, temperature, panelWatts, panelCount,
kwp, tracking, mounting, gamma, defaultTilt, tilt, azimuth, albedo, losses, inverterOn, acRating,
efficiency,
};
}
// The sunlight inputs for the model: the user's own values, or the NASA data at the location.
export function sunlightFor(s, grid) {
if (s.ownData) {
return {ghi: s.ghi, diffuse: null, temperature: s.temperature, albedo: null};
}
if (!grid || s.latitude === null || s.longitude === null) {
return null;
}
return lookupClimatology(grid, s.latitude, s.longitude);
}
// What stops an estimate, or an empty list when it can run.
export function missingInputs(s, sunlight) {
const missing = [];
if (s.latitude === null) {
missing.push('a latitude');
}
if (!s.ownData && s.longitude === null) {
missing.push('a longitude');
}
if (s.ownData && s.ghi.some(v => v === null)) {
missing.push('sunlight for all 12 months');
}
if (!(s.kwp > 0)) {
missing.push('panel watts and count');
}
if (missing.length === 0 && (!sunlight || sunlight.ghi.some(v => v === null))) {
missing.push('a location with sunlight data');
}
return missing;
}
const modelInputs = (s, sunlight) => ({
latitude: s.latitude,
ghi: sunlight.ghi,
diffuse: sunlight.diffuse,
temperature: sunlight.temperature,
albedo: s.albedo ?? sunlight.albedo ?? undefined,
kwp: s.kwp,
tilt: s.tilt,
azimuth: s.azimuth,
tracking: s.tracking,
mounting: s.mounting,
gamma: s.gamma,
losses: s.losses,
inverter: s.inverterOn ? {acRating: s.acRating, efficiency: s.efficiency} : null,
});
const compassLabel = azimuth => {
const exact = COMPASS.find(c => Number(c.value) === azimuth);
return exact ? exact.label : `${azimuth}°`;
};
// Small explanatory text at the top of a collapsed section.
const Hint = ({children}) =>
{children}
;
// NASA POWER's requested acknowledgment, the license, and how WROLPi changed the data (CC BY 4.0).
function DataAttribution() {
return Data attribution
;
}
const ESTIMATE_INFO = 'A typical-year estimate from monthly averages. Real years vary; expect roughly ±10–15% '
+ 'over a year and more in any single month. Shading from trees and buildings is not modeled beyond the '
+ 'Shading loss.';
// Browsers only offer geolocation to pages served over HTTPS.
export const geolocationAvailable = () => Boolean(window.isSecureContext && navigator.geolocation);
const GEOLOCATION_ERRORS = {
1: 'Location permission was denied. Allow it in your browser\'s settings for this site.',
2: 'Your device could not find its location. Phones with GPS work offline; most computers need the Internet '
+ 'for this.',
3: 'Finding your location took too long. Phones with GPS work offline; most computers need the Internet for '
+ 'this.',
};
function LocationSection({get, set, s, climatology}) {
const [locating, setLocating] = React.useState(false);
const [geoError, setGeoError] = React.useState(null);
const latError = get('lat') && s.latitude === null ? 'Latitude must be between -90 and 90' : null;
const lonError = get('lon') && s.longitude === null ? 'Longitude must be between -180 and 180' : null;
const locate = () => {
setLocating(true);
setGeoError(null);
navigator.geolocation.getCurrentPosition(
({coords}) => {
setLocating(false);
// 4 decimals (about 11 m) is far finer than the 1° data and keeps the shared URL short.
set({lat: Number(coords.latitude.toFixed(4)), lon: Number(coords.longitude.toFixed(4))});
},
error => {
setLocating(false);
setGeoError(GEOLOCATION_ERRORS[error.code] || error.message);
},
{enableHighAccuracy: false, timeout: 20000, maximumAge: 10 * 60 * 1000},
);
};
// The data's attribution is at the bottom of the page; this line only reports the data's state.
let source = null;
if (s.ownData) {
source = 'Using your own sunlight data.';
} else if (climatology.loading) {
source = ;
} else if (climatology.error) {
source =
Enter your own monthly sunlight under "Use my own sunlight data" below.
;
}
return <>
1. Location set({lat: e.target.value})}/>
set({lon: e.target.value})}/>
{geoError && {geoError}}
{source &&
{source}
}
>;
}
function PanelsSection({setNumber, s}) {
return <>
2. Your panels setNumber('pw', v, DEFAULT_PANEL_WATTS)}/>
setNumber('pn', v, DEFAULT_PANEL_COUNT)}/>
{fmt(s.kwp * 1000, 0)} W total ({fmt(s.kwp)} kW)
>;
}
function Results({result, s}) {
const unit = s.inverterOn ? 'kWh AC' : 'kWh DC';
const rows = result.months.map(m => {m.month}{fmt(m.energyDaily)}{fmt(m.energy, 0)}{fmt(m.poa)}{fmt(m.dayLength, 1)} h);
return Estimate
Month{unit}/day{unit}/monthSun hours on panelDay length{rows}
;
}
function AngleSection({setNumber, s, sunlight, ready}) {
const compass = COMPASS.find(c => Number(c.value) === s.azimuth)?.value || null;
const applyOptimal = goal => setNumber('tilt', optimalTilt(modelInputs(s, sunlight), goal), s.defaultTilt);
const azimuthDefault = defaultAzimuth(s.latitude ?? 0);
if (s.tracking !== 'fixed') {
return
A tracking array turns to follow the sun, so it has no fixed angle. Change Tracking under Panel details
to set one.
;
}
return <>
Leave these alone unless your panels are already mounted. The default (tilted to your latitude, facing
the equator) is close to the best for the year. "Best for winter" suits off-grid systems that must get
through the darkest month.
setNumber('tilt', v, s.defaultTilt)}/>
setNumber('az', v, azimuthDefault)}/>
>;
}
function DetailsSection({set, setNumber, s}) {
const moduleType = Object.entries(MODULE_TYPES).find(([, m]) => m.gamma === s.gamma)?.[0] || 'custom';
return <>
The defaults suit a typical ground or pole mounted array of ordinary panels. The temperature coefficient
is on your panel's datasheet; panels lose this much power for each °C they run above 25 °C.
setNumber('gamma', v, MODULE_TYPES.standard.gamma)}/>
set({alb: v === '' ? null : v})}/>
>;
}
function LossesSection({set, s}) {
const setLoss = (index, value) => {
const next = [...s.losses];
next[index] = value === '' ? LOSS_CATEGORIES[index].default : Number(value);
const isDefault = next.every((v, i) => v === DEFAULT_LOSSES[i]);
set({losses: isDefault ? null : formatMonthly(next)});
};
return <>
Real systems lose some power to dirt, wiring, shading and more. These are PVWatts' defaults. Raise Shading
if trees or buildings shade your panels, or Snow if snow sits on them for weeks.
{LOSS_CATEGORIES.map((c, i) => setLoss(i, v)}/>
)}
>;
}
function InverterSection({set, setNumber, s}) {
return <>
Leave this off if your panels charge batteries through a charge controller. Turn it on to see AC output
from a grid-tie or hybrid inverter.
set({inv: e.currentTarget.checked ? '1' : null})}/>
{s.inverterOn && setNumber('iac', v, roundDigits(s.kwp / 1.2, 2))}/>
setNumber('ieff', v, INVERTER_NOMINAL_EFFICIENCY)}/>
}
>;
}
function OwnDataSection({set, s, nasa}) {
const unit = s.fahrenheit ? '°F' : '°C';
// Start from the NASA values, when available, so the user edits rather than types all 24.
const enable = on => {
if (!on) {
set({ghi: null, temp: null});
return;
}
const ghi = nasa ? nasa.ghi.map(v => (v === null ? '' : roundDigits(v, 2))) : Array(12).fill('');
const temp = nasa
? nasa.temperature.map(v => (v === null ? '' : roundDigits(s.fahrenheit ? cToF(v) : v, 1)))
: Array(12).fill('');
// An all-blank list is still written for sunlight, so the section stays on for typing.
set({ghi: formatMonthly(ghi), temp: nasa ? formatMonthly(temp) : null});
};
// Convert the temperatures with the unit, so they stay the same physical temperatures.
const switchUnits = toFahrenheit => {
const temps = s.temperatureInput.map(v => (v === null ? null
: roundDigits(toFahrenheit ? cToF(v) : fToC(v), 1)));
set({tu: toFahrenheit ? 'f' : null, temp: temps.some(v => v !== null) ? formatMonthly(temps) : null});
};
const setMonth = (key, values, index, value) => {
const next = [...values];
next[index] = value === '' ? null : value;
set({[key]: formatMonthly(next)});
};
const rows = MONTH_NAMES.map((name, i) => {name} setMonth('ghi', s.ghi, i, v)}/>
setMonth('temp', s.temperatureInput, i, v)}/>
);
return <>
Only needed if you have better local measurements than the built-in data, for example in mountains, where
a 1° grid cell (about 69 miles across) can average very different terrain. Sunlight is global horizontal
irradiance in kWh/m²/day, the same as "peak sun hours" on flat ground. Blank temperatures use 20 °C.
enable(e.currentTarget.checked)}/>
{s.ownData && switchUnits(e.currentTarget.checked)}/>}
{s.ownData &&
Estimate what solar panels will produce over a typical year. Enter a location and your panels; everything
else has sensible defaults. Settings are saved in the page address, so you can bookmark or share them.
set({tab: v === 'offgrid' ? v : null})} keepMounted={false}
style={{marginTop: '1.5em'}}>
EstimateOff-grid sizing
{ready && }
{!ready && !waitingForData &&