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_SOURCE, 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}
; 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}, ); }; let source; if (s.ownData) { source = 'Using your own sunlight data.'; } else if (climatology.loading) { source =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.