Open the Solar calculator from the map, pins and current location

The map's right-click (or long-press) menu gains "Calculate Solar
Performance", and each saved pin a sun button; both open the calculator at
that location.  A button beside Latitude fills in the browser's current
location.  Locations are rounded to 4 decimals, and longitudes from a map
panned around the world are wrapped back to -180..180.

The map removed lat/lon/z from the URL when it closed, even after navigating
to another page, which stripped the calculator's location from its URL (and
from links shared with the Share button).  It now only cleans up while the
URL is still a map page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-04 17:09:33 -06:00
parent 4f06dfe9c8
commit b5ea2054c1
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
9 changed files with 203 additions and 22 deletions

View file

@ -20,6 +20,7 @@ import {Media, StatusContext} from "../contexts/contexts";
import {MAP_VIEWER_URI} from "./Vars";
import MapViewer from "./MapViewer";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {solarCalculatorPath} from "./calculators/solar";
import maplibregl from "maplibre-gl";
import {Protocol} from "pmtiles";
import layers from "protomaps-themes-base";
@ -567,6 +568,9 @@ function MapPins() {
navigate(`/map?lat=${pin.lat}&lon=${pin.lon}&z=14`);
};
const solarButton = (pin) => <Button size='xs' icon='sun' aria-label={`Solar estimate for ${pin.label}`}
onClick={() => navigate(solarCalculatorPath(pin.lat, pin.lon))}/>;
// --- Desktop headers and row ---
const fullHeaders = [
{key: 'color', text: '', sortBy: i => i.color},
@ -600,10 +604,11 @@ function MapPins() {
</Table.Cell>
<Table.Cell>{pin.created}</Table.Cell>
<Table.Cell>
{/* See PinEditRow: a Group so the three controls line up and are spaced. */}
{/* See PinEditRow: a Group so the controls line up and are spaced. */}
<Group gap='xs' wrap='nowrap'>
<Button size='xs' icon='edit' aria-label={`Edit ${pin.label}`}
onClick={() => setEditingId(pin.id)}/>
{solarButton(pin)}
<AddToPlaylistButton
size='xs'
icon='list'
@ -646,15 +651,18 @@ function MapPins() {
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</div>
</Table.Cell>
<Table.Cell>
<APIButton
size='xs'
role='danger'
icon='trash'
aria-label={`Delete ${pin.label}`}
confirmContent='Delete this pin?'
confirmButton='Delete'
onClick={() => handleDelete(pin.id)}
/>
<Group gap='xs' wrap='nowrap'>
{solarButton(pin)}
<APIButton
size='xs'
role='danger'
icon='trash'
aria-label={`Delete ${pin.label}`}
confirmContent='Delete this pin?'
confirmButton='Delete'
onClick={() => handleDelete(pin.id)}
/>
</Group>
</Table.Cell>
</Table.Row>;
};

View file

@ -1,5 +1,5 @@
import React from 'react';
import {act, screen} from '@testing-library/react';
import {act, fireEvent, screen} from '@testing-library/react';
import {Route, Routes} from 'react-router';
import {renderWithProviders as render} from '../test-utils';
import {MapRoute} from './Map';
@ -92,6 +92,16 @@ describe('the Pins tab', () => {
expect(screen.getAllByText('Camp').length).toBeGreaterThan(0);
expect(screen.queryAllByText(NO_PINS)).toHaveLength(0);
});
test('a pin opens the Solar calculator at its location', async () => {
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.12346, lon: -111.2, label: 'Camp', color: '#f00'}]});
renderAt('/map/pins');
await act(async () => {
});
fireEvent.click(screen.getAllByRole('button', {name: 'Solar estimate for Camp'})[0]);
expect(window.location.pathname).toBe('/more/calculators');
expect(window.location.search).toBe('?calc=solar&lat=40.1235&lon=-111.2');
});
});
describe('the Manage tab subscriptions table', () => {

View file

@ -1,5 +1,5 @@
import React, {useCallback, useContext, useEffect, useRef, useState} from "react";
import {useSearchParams} from "react-router";
import {useNavigate, useSearchParams} from "react-router";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import {Protocol} from "pmtiles";
@ -11,6 +11,7 @@ import {Button, Checkbox, Header, Icon, Panel, TextInput, Toggle} from "./ui";
import {SettingsContext, ThemeContext} from "../contexts/contexts";
import {mapFlavor, mapSprite} from "../themes/names";
import {poiPopupHtml} from "./mapPoiPopup";
import {solarCalculatorPath} from "./calculators/solar";
// Terrain DEM file prefix for hillshade and contours.
const TERRAIN_PREFIX = "terrain-";
@ -531,6 +532,7 @@ export default function MapViewer() {
const [mapReady, setMapReady] = useState(false);
const [error, setError] = useState(null);
const [contextMenu, setContextMenu] = useState(null);
const navigate = useNavigate();
const [addingPin, setAddingPin] = useState(null); // {lat, lon} when pin dialog is open
const markersRef = useRef([]);
const pinsVisibleRef = useRef(true);
@ -772,12 +774,16 @@ export default function MapViewer() {
}
mapRef.current = null;
setMapReady(false);
// Clean up map params from URL so they don't leak to other pages.
// Clean up map params from URL so they don't leak to other pages. Only while the URL is
// still a map page: after navigating away, lat/lon belong to the new page (the Solar
// calculator, for one).
const url = new URL(window.location);
url.searchParams.delete("lat");
url.searchParams.delete("lon");
url.searchParams.delete("z");
window.history.replaceState(null, '', url.pathname + url.search);
if (url.pathname.startsWith("/map")) {
url.searchParams.delete("lat");
url.searchParams.delete("lon");
url.searchParams.delete("z");
window.history.replaceState(null, '', url.pathname + url.search);
}
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
@ -923,6 +929,12 @@ export default function MapViewer() {
setContextMenu(null);
}, [contextMenu]);
const handleSolar = useCallback(() => {
if (!contextMenu) return;
setContextMenu(null);
navigate(solarCalculatorPath(contextMenu.lat, contextMenu.lon));
}, [contextMenu, navigate]);
const handleSetDefaultLocation = useCallback(async () => {
const map = mapRef.current;
if (!map) return;
@ -999,6 +1011,14 @@ export default function MapViewer() {
>
Add Pin Here
</div>
<div
style={{padding: "0.5rem 0.75rem", cursor: "pointer", userSelect: "none"}}
onMouseEnter={e => e.target.style.background = "#f0f0f0"}
onMouseLeave={e => e.target.style.background = "transparent"}
onClick={handleSolar}
>
Calculate Solar Performance
</div>
<div
style={{padding: "0.5rem 0.75rem", cursor: "pointer", userSelect: "none"}}
onMouseEnter={e => e.target.style.background = "#f0f0f0"}

View file

@ -0,0 +1,45 @@
import React from 'react';
import {renderWithProviders as render} from '../test-utils';
import MapViewer from './MapViewer';
// MapLibre needs WebGL, which jsdom lacks; these tests only cover what the viewer does to the URL.
jest.mock('maplibre-gl', () => ({
__esModule: true,
default: {Map: class {
}, addProtocol: jest.fn(), Marker: class {
}, Popup: class {
}},
}));
jest.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
jest.mock('pmtiles', () => ({
__esModule: true, Protocol: class {
tile = jest.fn();
},
}));
jest.mock('protomaps-themes-base', () => ({__esModule: true, default: () => []}));
jest.mock('@acalcutt/maplibre-contour-pmtiles', () => ({__esModule: true, default: {}}));
jest.mock('../api', () => ({
...jest.requireActual('../api'),
// Never resolves: the map never initializes, which these tests do not need.
getMapFiles: jest.fn(() => new Promise(() => {
})),
getMapPins: jest.fn(() => new Promise(() => {
})),
}));
describe('the map position in the URL', () => {
test('is removed when the map closes', () => {
const {unmount} = render(<MapViewer/>, {route: '/map?lat=40&lon=-105&z=8&layer=a'});
unmount();
expect(window.location.pathname).toBe('/map');
expect(window.location.search).toBe('?layer=a');
});
test('is not removed from the page the map navigated to', () => {
// "Calculate Solar Performance" navigates to a page whose own lat/lon must survive the map closing.
const {unmount} = render(<MapViewer/>, {route: '/map?lat=40&lon=-105&z=8'});
window.history.pushState({}, '', '/more/calculators?calc=solar&lat=40.0154&lon=-105.2705');
unmount();
expect(window.location.search).toBe('?calc=solar&lat=40.0154&lon=-105.2705');
});
});

View file

@ -6,6 +6,7 @@ import {
Grid,
Group,
Header,
IconButton,
Loader,
Message,
NumberInput,
@ -191,10 +192,40 @@ const ESTIMATE_INFO = 'A typical-year estimate from monthly averages. Real years
+ '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.';
@ -210,18 +241,23 @@ function LocationSection({get, set, s, climatology}) {
return <>
<Header as='h3'>1. Location</Header>
<Grid>
<Grid.Col span={{base: 12, xs: 6}}>
<Grid align='flex-end'>
<Grid.Col span='content'>
<IconButton icon='current location' label='Use my current location' size='input-sm'
loading={locating} disabled={!geolocationAvailable()} onClick={locate}/>
</Grid.Col>
<Grid.Col span='auto'>
<TextInput label='Latitude' placeholder='40.015 or 40°0′54″N' name='lat'
value={get('lat') || ''} error={latError}
onChange={e => set({lat: e.target.value})}/>
</Grid.Col>
<Grid.Col span={{base: 12, xs: 6}}>
<Grid.Col span={{base: 12, xs: 'auto'}}>
<TextInput label='Longitude' placeholder='-105.27 or 105°16′12″W' name='lon'
value={get('lon') || ''} error={lonError}
onChange={e => set({lon: e.target.value})}/>
</Grid.Col>
</Grid>
{geoError && <Message kind='warning' title='Could not get your location'>{geoError}</Message>}
<div style={{fontSize: '0.85em', opacity: 0.75, marginTop: '0.5em'}}>{source}</div>
</>;
}
@ -509,8 +545,9 @@ export function SolarCalculator() {
<PanelsSection setNumber={setNumber} s={s}/>
{ready && <Results result={result} s={s}/>}
{!ready && !waitingForData &&
<Message kind='info' title='Almost there'>Enter {missing.join(', ')} to see an estimate.</Message>}
{!ready && !waitingForData && <div style={{marginTop: '1em'}}>
<Message kind='info' title='Almost there'>Enter {missing.join(', ')} to see an estimate.</Message>
</div>}
<Header as='h3' style={{marginTop: '1.5em'}}>Fine-tune (optional)</Header>
<Accordion multiple>

View file

@ -134,6 +134,43 @@ describe('SolarCalculator', () => {
expect(currentParams().has('pn')).toBe(false);
});
describe('use my current location', () => {
const withGeolocation = getCurrentPosition => {
Object.defineProperty(window, 'isSecureContext', {value: true, configurable: true});
Object.defineProperty(navigator, 'geolocation', {value: {getCurrentPosition}, configurable: true});
};
afterEach(() => {
delete window.isSecureContext;
delete navigator.geolocation;
});
test('fills in the location, rounded to 4 decimals', async () => {
withGeolocation(success => success({coords: {latitude: 39.7392358, longitude: -104.990251}}));
renderWithProviders(<SolarCalculator/>, {route: BASE});
fireEvent.click(screen.getByRole('button', {name: 'Use my current location'}));
expect(currentParams().get('lat')).toBe('39.7392');
expect(currentParams().get('lon')).toBe('-104.9903');
expect(screen.getByLabelText('Latitude')).toHaveValue('39.7392');
expect(await findEstimate()).toBeInTheDocument();
});
test('explains a denied permission', () => {
withGeolocation((success, failure) => failure({code: 1, message: 'User denied Geolocation'}));
renderWithProviders(<SolarCalculator/>, {route: BASE});
fireEvent.click(screen.getByRole('button', {name: 'Use my current location'}));
expect(screen.getByText('Could not get your location')).toBeInTheDocument();
expect(screen.getByText(/Location permission was denied/)).toBeInTheDocument();
expect(currentParams().has('lat')).toBe(false);
});
test('is disabled without HTTPS', () => {
Object.defineProperty(window, 'isSecureContext', {value: false, configurable: true});
renderWithProviders(<SolarCalculator/>, {route: BASE});
expect(screen.getByRole('button', {name: 'Use my current location'})).toBeDisabled();
});
});
test('an invalid latitude is flagged', () => {
renderWithProviders(<SolarCalculator/>, {route: `${BASE}&lat=95`});
expect(screen.getByText('Latitude must be between -90 and 90')).toBeInTheDocument();

View file

@ -470,3 +470,12 @@ export function parseMonthly(text) {
export function formatMonthly(values) {
return values.map(v => (v === null || v === undefined || v === '' ? '' : `${v}`)).join(',');
}
// Link to the Solar calculator for a location, e.g. from the map. 4 decimals (about 11 m) is far finer
// than the 1° data and keeps the shared URL short. MapLibre reports longitudes past ±180° once the map
// has been panned around the world, so those are wrapped back.
export function solarCalculatorPath(latitude, longitude) {
const lon = longitude >= -180 && longitude <= 180 ? longitude : ((longitude + 180) % 360 + 360) % 360 - 180;
const round = value => Number(value.toFixed(4));
return `/more/calculators?calc=solar&lat=${round(latitude)}&lon=${round(lon)}`;
}

View file

@ -20,6 +20,7 @@ import {
parseCoordinate,
parseMonthly,
poaIrradiance,
solarCalculatorPath,
sunPosition,
sunsetHourAngle,
totalHourlyRatio,
@ -308,3 +309,16 @@ describe('input parsing', () => {
expect(parseMonthly(formatMonthly(GHI_40N))).toEqual(GHI_40N);
});
});
describe('solarCalculatorPath', () => {
test('links to the calculator with the location rounded to 4 decimals', () => {
expect(solarCalculatorPath(40.0153812, -105.2705456))
.toBe('/more/calculators?calc=solar&lat=40.0154&lon=-105.2705');
});
test('wraps a longitude from a map that has been panned around the world', () => {
expect(solarCalculatorPath(10, 190)).toBe('/more/calculators?calc=solar&lat=10&lon=-170');
expect(solarCalculatorPath(10, -540.5)).toBe('/more/calculators?calc=solar&lat=10&lon=179.5');
expect(solarCalculatorPath(10, 180)).toBe('/more/calculators?calc=solar&lat=10&lon=180');
});
});

View file

@ -60,6 +60,7 @@ const iconNameAliases: Record<string, keyof typeof Tabler> = {
'comments': 'IconMessages',
'copy': 'IconCopy',
'cube': 'IconCube',
'current location': 'IconCurrentLocation',
'directory': 'IconFolder',
'disk': 'IconDatabase',
'dot circle': 'IconCircleDot',