wrolpi/app/src/components/calculators/HamCalculators.js
Roland a74e4c6fc4
fix: break the import cycle that put useCalculators in the TDZ
The dashboard threw on arrival from any other page:

    ReferenceError: Cannot access 'useCalculators' before initialization
        at Module.useCalculators
        at DashboardCalculators

`Calculators.js` exports `useCalculators` as a `const` and imports the ten
calculators it renders.  Five of those reached back up to `Apps.js` for
`ColoredInput`, and `Apps.js` imports `CalculatorsPage` from
`Calculators.js` -- so the hub was in a cycle with its own leaves:

    Calculators.js -> calculators/ElectricalCalculators.js
                   -> Apps.js -> Calculators.js

Webpack compiles a `const` export to a live getter, and a getter read
before the module body reaches the declaration THROWS rather than
returning undefined.  That is the whole mechanism behind this particular
error, and it names the const it could not reach.

`ColoredInput` is a text field with a Label welded to one edge -- the
calculators' unit markers.  It has no business in the module that ROUTES
to the calculators, so it moved to `components/ui/Inputs.tsx`.  Nothing in
`components/ui` imports from `components/`, so a control kept there cannot
close a loop like this again.  Gallery entry added, per the standing rule.

`src/import-cycles.test.js` is the guard: a small import-graph walker,
scoped to hubs that export a `const` into their own subtree.  It fails
with the cycle printed, and it self-checks against a known cycle so it
cannot pass by finding nothing.  Verified red with the cycle planted back.

HONEST LIMIT: the guard is static because I could not reproduce the
RUNTIME error in a test.  TDZ needs a module to be mid-evaluation when the
getter is read, and by the time any spec body runs every module has
finished; babel also papers over it, handing back undefined where webpack
throws.  I tried an e2e that navigates to the dashboard and collects
window errors -- it passes with the cycle present, so it would have been a
test that cannot fail for the reason it claims, and I deleted it rather
than ship it.  A react-refresh trigger did not reproduce it either.  What
is checkable, and what is genuinely the defect, is the cycle.

1080 jest / 60 suites, 158 in ui-layout.cy.js, clean build.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 18:05:47 -06:00

329 lines
11 KiB
JavaScript

import React from "react";
import {ColoredInput, Grid, Header, Table} from "../ui";
import {roundDigits} from "../Common";
// ---------------------------------------------------------------------------
// Pure antenna math
//
// Wire antennas are shorter than free-space wavelength by ~5% (end effect).
// The ARRL / ham-radio constants are:
// full-wave length (ft) = 936 / f(MHz)
// half-wave dipole (ft) = 468 / f(MHz) = full * 0.5
// quarter-wave (ft) = 234 / f(MHz) = full * 0.25
// 5/8-wave (ft) = 585 / f(MHz) = full * 0.625
// Free-space wavelength uses the exact speed of light and is shown separately.
// ---------------------------------------------------------------------------
/** Speed of light in free space (m/s). */
export const SPEED_OF_LIGHT = 299792458;
/**
* Feet of wire for one full electrical wavelength, including end-effect.
* Free-space equivalent is ~984 / f; 936/984 ≈ 0.95 velocity factor.
*/
export const FULL_WAVE_FEET_PER_MHZ = 936;
/** Common antenna fractions shown in the calculator. */
export const ANTENNA_FRACTIONS = [
{name: '½ Antenna Length', multiplier: 0.5},
{name: '¼ Antenna Length', multiplier: 0.25},
{name: '⅝ Antenna Length', multiplier: 0.625},
];
/**
* Convert a decimal foot length into whole feet and inches.
* Rounds to the nearest inch and carries 12 inches into an extra foot
* (e.g. 3.96 ft → 4 ft 0 in, never "3 ft 12 in").
*
* @param {number} decimalFeet
* @returns {[number, number]} [feet, inches]
*/
export function convertFeetToFeetAndInches(decimalFeet) {
if (!Number.isFinite(decimalFeet) || decimalFeet < 0) {
return [0, 0];
}
const totalInches = Math.round(decimalFeet * 12);
const feet = Math.floor(totalInches / 12);
const inches = totalInches % 12;
return [feet, inches];
}
/**
* Full-wave wire-antenna length in feet for a given frequency in MHz.
* Returns null when frequency is not a positive finite number.
*
* @param {number} mhz
* @returns {number|null}
*/
export function fullWaveFeet(mhz) {
if (!Number.isFinite(mhz) || !(mhz > 0)) {
return null;
}
return FULL_WAVE_FEET_PER_MHZ / mhz;
}
/**
* Free-space wavelength in meters for a given frequency in MHz.
* λ = c / f. Returns null when frequency is not positive.
*
* @param {number} mhz
* @returns {number|null}
*/
export function freeSpaceWavelengthMeters(mhz) {
if (!Number.isFinite(mhz) || !(mhz > 0)) {
return null;
}
return SPEED_OF_LIGHT / (mhz * 1e6);
}
/**
* Frequency in MHz from a free-space wavelength in meters.
* f = c / λ. Returns null when wavelength is not positive.
*
* @param {number} meters
* @returns {number|null}
*/
export function frequencyMhzFromWavelengthMeters(meters) {
if (!Number.isFinite(meters) || !(meters > 0)) {
return null;
}
return SPEED_OF_LIGHT / meters / 1e6;
}
/**
* Convert a full-wave length in feet into the unit set used by the UI.
*
* @param {number} feetValue - full-wave length in feet
* @returns {{feet: number, inches: number, meters: number, cm: number}}
*/
export function lengthUnitsFromFeet(feetValue) {
const meters = feetValue * 0.3048;
return {
feet: feetValue,
inches: feetValue * 12,
meters,
cm: meters * 100,
};
}
/**
* Scale a length-unit set by a fraction (0.5 half-wave, 0.25 quarter, etc.).
*
* @param {{feet: number, inches: number, meters: number, cm: number}} units
* @param {number} multiplier
* @returns {{feet: number, inches: number, meters: number, cm: number}}
*/
export function scaleLengthUnits(units, multiplier) {
return {
feet: units.feet * multiplier,
inches: units.inches * multiplier,
meters: units.meters * multiplier,
cm: units.cm * multiplier,
};
}
/**
* All length units for the full-wave wire antenna at a given frequency.
* Returns null when frequency is invalid.
*
* @param {number} mhz
* @returns {{feet: number, inches: number, meters: number, cm: number}|null}
*/
export function fullWaveLengthUnits(mhz) {
const feet = fullWaveFeet(mhz);
if (feet === null) {
return null;
}
return lengthUnitsFromFeet(feet);
}
/**
* Antenna total length and per-leg length for a fraction of a full wave.
* "Leg length" is half the total (center-fed dipole legs).
*
* @param {number} mhz
* @param {number} multiplier - e.g. 0.5 for half-wave
* @returns {{
* total: {feet: number, inches: number, meters: number, cm: number, feetInches: [number, number]},
* leg: {feet: number, inches: number, meters: number, cm: number, feetInches: [number, number]},
* }|null}
*/
export function antennaFractionLengths(mhz, multiplier) {
const full = fullWaveLengthUnits(mhz);
if (full === null || !Number.isFinite(multiplier)) {
return null;
}
const total = scaleLengthUnits(full, multiplier);
const leg = scaleLengthUnits(total, 0.5);
return {
total: {
...total,
feetInches: convertFeetToFeetAndInches(total.feet),
},
leg: {
...leg,
feetInches: convertFeetToFeetAndInches(leg.feet),
},
};
}
// ---------------------------------------------------------------------------
// UI
// ---------------------------------------------------------------------------
const defaultMhzInputValue = '144.2';
export function DipoleAntennaCalculator() {
const [mhz, setMhz] = React.useState(144.2);
const [mhzInputValue, setMhzInputValue] = React.useState(defaultMhzInputValue);
const [waveInputValue, setWaveInputValue] = React.useState(0);
const [feet, setFeet] = React.useState(0);
const [inches, setInches] = React.useState(0);
const [meters, setMeters] = React.useState(0);
const [cm, setCM] = React.useState(0);
React.useEffect(() => {
const units = fullWaveLengthUnits(mhz);
if (!units) {
setFeet(0);
setInches(0);
setMeters(0);
setCM(0);
setWaveInputValue('');
return;
}
setFeet(units.feet);
setInches(units.inches);
setMeters(units.meters);
setCM(units.cm);
setWaveInputValue(roundDigits(freeSpaceWavelengthMeters(mhz)));
}, [mhz]);
const mhzStorageKey = 'dipole_mhz';
const storageMhzValue = localStorage.getItem(mhzStorageKey);
React.useEffect(() => {
if (storageMhzValue) {
const parsed = parseFloat(storageMhzValue);
if (parsed > 0) {
setMhz(parsed);
setMhzInputValue(storageMhzValue);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleMhzChange = (value) => {
setMhzInputValue(value);
const parsed = parseFloat(value);
// Require a finite positive frequency so overflow (e.g. 1e999 → Infinity) does not stick.
setMhz(value && Number.isFinite(parsed) && parsed > 0 ? parsed : 0);
localStorage.setItem(mhzStorageKey, value);
}
const handleWaveChange = (value) => {
setWaveInputValue(value);
const parsed = parseFloat(value);
if (value && Number.isFinite(parsed) && parsed > 0) {
const newMhz = frequencyMhzFromWavelengthMeters(parsed);
if (newMhz === null) {
// Conversion failed (should not happen for finite positive λ); treat as invalid.
setMhz(0);
setMhzInputValue('');
localStorage.setItem(mhzStorageKey, '');
return;
}
setMhz(newMhz);
setMhzInputValue(roundDigits(newMhz));
localStorage.setItem(mhzStorageKey, String(roundDigits(newMhz)));
} else {
// Cleared / zero / non-finite wavelength: drop stale MHz and table results.
setMhz(0);
setMhzInputValue('');
localStorage.setItem(mhzStorageKey, '');
}
}
const [mhzSelected, setMhzSelected] = React.useState(true);
const handleClick = (e, name) => {
if (name === 'mhz') {
setMhzSelected(true);
} else {
setMhzSelected(false);
}
}
return <>
<Header as='h2'>Dipole Antenna</Header>
<Grid>
<Grid.Col span={{base: 12, sm: 6}}>
<ColoredInput fluid
label='MHz'
labelPosition='right'
value={mhzInputValue}
onChange={e => handleMhzChange(e.target.value)}
onSelect={e => handleClick(e, 'mhz')}
color={mhzSelected ? null : 'grey'}
/>
</Grid.Col>
<Grid.Col span={{base: 12, sm: 6}}>
<ColoredInput fluid
label='Wavelength'
labelPosition='right'
value={waveInputValue}
onChange={e => handleWaveChange(e.target.value)}
onSelect={e => handleClick(e, 'wave')}
color={mhzSelected ? 'grey' : null}
/>
</Grid.Col>
</Grid>
{ANTENNA_FRACTIONS.map(i => {
const [feet_, inches_] = convertFeetToFeetAndInches(feet * i.multiplier);
const [half_feet, half_inches] = convertFeetToFeetAndInches(feet * i.multiplier / 2);
return <Table key={i.name} style={{marginTop: '1em'}}>
<Table.Header>
<Table.Row>
<Table.HeaderCell>{i.name}</Table.HeaderCell>
<Table.HeaderCell>Leg Length</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
{feet_} ft. {inches_} in.
</Table.Cell>
<Table.Cell>
{half_feet} ft. {half_inches} in.
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
{roundDigits(inches * i.multiplier)} inches
</Table.Cell>
<Table.Cell>
{roundDigits(inches * i.multiplier / 2)} inches
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
{roundDigits(meters * i.multiplier)} meters
</Table.Cell>
<Table.Cell>
{roundDigits(meters * i.multiplier / 2)} meters
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
{roundDigits(cm * i.multiplier)} cm.
</Table.Cell>
<Table.Cell>
{roundDigits(cm * i.multiplier / 2)} cm.
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
})}
</>
}