wrolpi/app/src/components/calculators/WaterCalculator.js
Roland 906705e5b4 ui: thirty-five files off Semantic, leaving fifteen
Phase 2, part 4.  Baseline 50 -> 15.

Migrated: all eight calculators, the rest of inventory and collections, the
Map/Zim/Docs cluster, Videos, Files, Search, Archive, DashboardPage,
DatesSelector, HelpModal, Events, Tags, Flasher's neighbours, admin Settings
and Status, Download, and App.

Also the three shared modules everything imports: api.js and customHooks.js
swap the Semantic toast library for the library's shim (same call shape), and
useForm.js renders the library's Message.  useForm accepts both the old
`{content, header, positive|negative}` shape and the new `{kind, title}`,
because the pages building those objects migrate separately.

Two library gaps closed, both found by call sites needing them:

  ActionInput is a forwardRef now.  Its ref reaches the input rather than the
  wrapper, because callers use it to focus or select the field -- a ref to the
  surrounding div would do neither, which is why one call site had resorted to
  hand-copying the component's markup.

  Header takes a `color` token name.  Three separate call sites had reached for
  an inline style to colour a heading that carries meaning ("3 items to add"
  against "2 to remove"), which is how a hex ends up in markup.

Two files needed repair after being interrupted mid-edit: MapViewer had a
Segment left in its error branch, and VideoPlayer had lost the useContext
import its own code still used.  Neither jest nor tsc noticed; only
`npm run build` did, which is the whole reason that check exists.

Fifteen files remain: Archive, BulkTagModal, Channels, Docs, FileBrowser,
FilePreview, Flasher, Nav, Playlists, Theme.tsx, Upload, VideoPlayer, Zim,
ControllerPage, admin/Downloads.  Theme.tsx is deliberately last -- the
unmigrated files still import its Semantic-backed wrappers, so it can only go
once they have.
2026-07-30 12:54:24 -06:00

371 lines
17 KiB
JavaScript

import React from "react";
import {Button, Grid, Group, Header, NumberInput, Panel, Table} from "../ui";
import {InfoPopup, roundDigits, Toggle, useLocalStorage} from "../Common";
// Pure calculation functions for the Water Storage calculator.
//
// The model is deliberately simple: a household of some men, women, and children each
// consume a per-day amount of water (drinking plus hygiene/dish use). Over a chosen
// duration that becomes a total volume, which the user stores in some number of a chosen
// container (55-gallon drums, 5-gallon buckets, 2-liter bottles, ...).
//
// Functions are unit-agnostic: pass consistent units (all gallons, or all liters) and the
// result comes back in those same units. The React component picks imperial vs metric and
// supplies the matching per-category rates and container capacities.
// Total water the household needs per day: sum of (count * rate) for each category.
// Missing/blank/non-positive counts or rates contribute nothing rather than NaN.
export function dailyDemand(counts, rates) {
const term = (count, rate) => {
const c = Number(count), r = Number(rate);
return (c > 0 && r > 0) ? c * r : 0;
};
return term(counts.men, rates.men)
+ term(counts.women, rates.women)
+ term(counts.children, rates.children)
+ term(counts.pregnant, rates.pregnant);
}
// Total volume to store for `days` days at the given daily demand.
export function totalWater(daily, days) {
if (!(daily > 0) || !(days > 0)) {
return null;
}
return daily * days;
}
// Number of containers of `capacity` needed to hold `totalVolume`, rounded up because a
// partial container still has to be a whole container. `leftover` is the unused capacity
// in the last container. Returns null for impossible inputs.
export function containersNeeded(totalVolume, capacity) {
if (!(totalVolume > 0) || !(capacity > 0)) {
return null;
}
const count = Math.ceil(totalVolume / capacity);
return {count, leftover: count * capacity - totalVolume};
}
// Approximate weight of a volume of water: ~8.345 lb per US gallon, or 1 kg per liter.
// Useful for shelving/vehicle planning. Returns null when the volume is not positive.
export function waterWeight(volume, metric) {
if (!(volume > 0)) {
return null;
}
return metric ? volume : volume * 8.345;
}
/**
* Pure function that computes the main derived values the UI shows,
* given the same inputs the component works with. This is primarily
* exposed to enable high-quality lifecycle / integration-style tests.
*/
export function computeStorage({ counts, rates, extra = '', days, metric = false }) {
const baseDaily = dailyDemand(counts, rates);
const extraDaily = Number(extra) > 0 ? Number(extra) : 0;
const daily = baseDaily + extraDaily;
const total = totalWater(daily, days);
const weight = waterWeight(total, metric);
// Convenient container results for common sizes used in tests
const bucketCapacity = metric ? 18.9 : 5; // ~5 gal bucket or ~19 L
const bucket = total !== null ? containersNeeded(total, bucketCapacity) : null;
const ibcCapacity = metric ? 1041 : 275;
const ibc = total !== null ? containersNeeded(total, ibcCapacity) : null;
return { daily, total, weight, bucket, ibc };
}
// Human-friendly label for a duration in days: days up to a week, then weeks, then months,
// then whole years. Keeps the slider from showing awkward values like "68 days".
export function formatDuration(days) {
const d = Math.round(Number(days));
if (!(d > 0)) {
return '—';
}
if (d <= 7) {
return `${d} day${d === 1 ? '' : 's'}`;
}
if (d < 30) {
const weeks = Math.round(d / 7);
return `${weeks} week${weeks === 1 ? '' : 's'}`;
}
if (d < 360) {
const months = Math.round(d / 30);
return `${months} month${months === 1 ? '' : 's'}`;
}
const years = d / 360;
if (Number.isInteger(years)) {
return `${years} year${years === 1 ? '' : 's'}`;
}
const months = Math.round(d / 30);
return `${months} months`;
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
// Per-category daily water need, including drinking plus hygiene and dish use. These are
// editable starting points. "Minimum" sits at the CDC/FEMA emergency floor of ~1 gallon
// per person per day (half drinking, half hygiene/cooking); men/women/children are scaled
// by the drinking portion using the National Academies adequate-intake figures (men ~3.7 L,
// women ~2.7 L of total water/day), while the hygiene/cooking half is shared. Pregnant and
// nursing women get the extra CDC/Ready.gov calls out (~+0.5 gal pregnant, ~+1 gal nursing;
// NAS lactating ~3.8 L). "Comfortable" roughly doubles the floor to allow real washing,
// cooking, and dishes. Metric values are the imperial values converted to liters and
// rounded; the component swaps tables on toggle.
export const WATER_PRESETS = {
minimum: {
label: 'Minimum',
description: 'CDC emergency floor (~1 gal/person/day)',
imperial: {men: 1.0, women: 0.9, children: 0.8, pregnant: 1.6}, // gallons/day
metric: {men: 3.8, women: 3.4, children: 3.0, pregnant: 6.1}, // liters/day
},
comfortable: {
label: 'Comfortable',
description: 'Adds real washing, cooking, and dishes',
imperial: {men: 2.0, women: 1.8, children: 1.5, pregnant: 2.8},
metric: {men: 7.6, women: 6.8, children: 5.7, pregnant: 10.6},
},
};
// Common water-storage containers, capacity in both gallons and liters. Ordered large to
// small so the dropdown reads from bulk storage down to single bottles.
export const CONTAINERS = [
{key: 'ibc', label: 'IBC tote', gallons: 275, liters: 1041},
{key: 'drum55', label: '55-gallon drum', gallons: 55, liters: 208},
{key: 'drum30', label: '30-gallon drum', gallons: 30, liters: 114},
{key: 'jug7', label: '7-gallon jug', gallons: 7, liters: 26.5},
{key: 'bucket5', label: '5-gallon bucket', gallons: 5, liters: 18.9},
{key: 'waterbrick', label: 'WaterBrick', gallons: 3.5, liters: 13.2},
{key: 'jug1', label: '1-gallon jug', gallons: 1, liters: 3.785},
{key: 'bottle2l', label: '2-liter soda bottle', gallons: 0.528, liters: 2},
{key: 'bottle1l', label: '1-liter bottle', gallons: 0.264, liters: 1},
{key: 'bottle500', label: '500 mL water bottle', gallons: 0.132, liters: 0.5},
];
// Slider stops in days: daily for the first week, then weekly, then monthly (grouped by 30
// per the "no awkward 68-day values" rule), out to a couple of years.
export const DURATION_STOPS = [
1, 2, 3, 4, 5, 6, 7,
14, 21,
30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360,
540, 720,
];
// Explanation shown in the "Daily Use" info popup. Cites the figures the presets are
// built from so the numbers are traceable offline.
const DEMAND_INFO = 'Per-person daily water includes drinking plus basic hygiene and dish '
+ 'washing — not just drinking. The Minimum preset follows the CDC/FEMA emergency floor '
+ 'of about 1 gallon (3.8 L) per person per day (roughly half for drinking, half for '
+ 'hygiene and cooking), and both agencies recommend storing a 2-week supply. The '
+ 'men/women/children split scales the drinking portion using the U.S. National Academies '
+ 'adequate-intake figures (men ~3.7 L, women ~2.7 L of total water per day). The '
+ 'Pregnant/Nursing category adds the extra CDC/Ready.gov calls out — about +0.5 gallon '
+ 'for pregnant and +1 gallon for nursing women. CDC also advises storing more for sick '
+ 'people, pets, and hot climates. Use the "Additional daily demand" field below for pets, '
+ 'livestock, or other needs not covered by the per-person categories.';
// Per-category colors (Paul Tol bright palette) so the count inputs read at a glance.
// These are diagram/legend colors matched to a fixed visual identity per category —
// not themed UI chrome — so they stay literal hex.
const CATEGORY_META = [
{key: 'men', label: 'Men', color: '#4477aa'},
{key: 'women', label: 'Women', color: '#aa3377'},
{key: 'children', label: 'Children', color: '#228833'},
{key: 'pregnant', label: 'Pregnant/Nursing', color: '#ee6677'},
];
// Pick black or white label text for legibility on a given background color.
function textColorFor(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
return luminance > 0.6 ? '#000000' : '#ffffff';
}
// Format a positive number with a unit, or an em-dash when unavailable.
function fmt(value, unit) {
if (!Number.isFinite(value) || value <= 0) {
return '—';
}
return unit ? `${roundDigits(value, 2)} ${unit}` : `${roundDigits(value, 2)}`;
}
// Keep a numeric input non-negative without disrupting in-progress decimal entry.
// A <input type=number> can only become negative via a leading "-", so stripping it is
// enough; returning the raw string otherwise lets the user finish typing "1.5".
export function clampNonNegative(value) {
if (value === '') {
return '';
}
return `${value}`.startsWith('-') ? `${value}`.slice(1) : value;
}
// A labeled numeric input whose label is tinted to match a category's diagram color.
// The color is a literal hex from CATEGORY_META, not a theme token, so this is a small
// local composition rather than the token-driven `Label`.
function SwatchInput({hex, label, value, onChange, name, min, step}) {
return <Group gap={0} wrap='nowrap' align='stretch' style={{marginBottom: '0.25em'}}>
<span style={{
display: 'flex', alignItems: 'center', padding: '0 10px', fontSize: 13, fontWeight: 500,
whiteSpace: 'nowrap', background: hex, color: textColorFor(hex), border: `1px solid ${hex}`,
}}>{label}</span>
<NumberInput name={name} value={value} onChange={onChange} min={min} step={step}
onFocus={e => e.target.select()} hideControls style={{flex: 1}}/>
</Group>;
}
export function WaterCalculator() {
const [metric, setMetric] = useLocalStorage('water_calculator_metric', false);
const [preset, setPreset] = useLocalStorage('water_calculator_preset', 'minimum');
const [counts, setCounts] = useLocalStorage('water_calculator_counts',
{men: '1', women: '1', children: '', pregnant: ''});
const [extra, setExtra] = useLocalStorage('water_calculator_extra', '');
const [rates, setRates] = React.useState({...WATER_PRESETS.minimum.imperial});
const [durationIndex, setDurationIndex] = useLocalStorage('water_calculator_duration_index',
DURATION_STOPS.indexOf(14));
// Reset the editable rates to the preset's defaults whenever the preset or unit changes.
// Fall back to the minimum preset if localStorage holds an unrecognized/stale key, so a
// bad persisted value can never crash the component on mount.
React.useEffect(() => {
const p = WATER_PRESETS[preset] ?? WATER_PRESETS.minimum;
setRates(metric ? {...p.metric} : {...p.imperial});
}, [preset, metric]);
const volumeUnit = metric ? 'L' : 'gal';
const rateUnit = metric ? 'L/day' : 'gal/day';
const weightUnit = metric ? 'kg' : 'lb';
// A persisted index could fall out of range if DURATION_STOPS ever changes; clamp it.
const durationStop = Math.min(Math.max(0, durationIndex), DURATION_STOPS.length - 1);
const days = DURATION_STOPS[durationStop];
const baseDaily = dailyDemand(counts, rates);
const extraDaily = Number(extra) > 0 ? Number(extra) : 0;
const daily = baseDaily + extraDaily;
const total = totalWater(daily, days);
const weight = waterWeight(total, metric);
// One count input per category, label colored to match.
const countInput = ({key, label, color}) =>
<SwatchInput hex={color} label={label} value={counts[key]} min={0} step={1} name={`count-${key}`}
onChange={value => setCounts({
...counts,
[key]: value === '' ? '' : String(Math.max(0, Math.round(Number(value)))),
})}/>;
// One editable rate input per category, sharing the category color.
const rateInput = ({key, label, color}) =>
<SwatchInput hex={color} label={label} value={rates[key]} min={0} step={0.1} name={`rate-${key}`}
onChange={value => setRates({...rates, [key]: clampNonNegative(value)})}/>;
const presetButtons = <Group gap='xs' style={{flexWrap: 'wrap'}}>
{Object.entries(WATER_PRESETS).map(([key, p]) => (
<Button key={key} type='button' role={preset === key ? 'primary' : 'cancel'}
onClick={() => setPreset(key)}>
{p.label} — {p.description}
</Button>
))}
<span style={{fontSize: '0.85em', opacity: 0.7}}>
(switching resets rates to preset defaults)
</span>
</Group>;
// One row per container: how many of it the total water would fill, and the spare
// capacity in the last one. Shown for every container so the user can compare.
const containerRows = CONTAINERS.map(c => {
const capacity = metric ? c.liters : c.gallons;
const need = total !== null ? containersNeeded(total, capacity) : null;
return <Table.Row key={c.key}>
<Table.Cell>{c.label}</Table.Cell>
<Table.Cell>{capacity} {volumeUnit}</Table.Cell>
<Table.Cell>
{need === null
? '—'
: <span><b>{need.count}</b>
{need.leftover > 0 &&
<span style={{opacity: 0.7}}> ({fmt(need.leftover, volumeUnit)} spare)</span>}
</span>}
</Table.Cell>
</Table.Row>;
});
return <div>
<Header as='h1'>Water Storage</Header>
<div style={{marginBottom: '1em'}}>
<Toggle label={metric ? 'Metric (liters)' : 'Imperial (gallons)'}
checked={metric} onChange={() => setMetric(!metric)}/>
</div>
<div style={{marginBottom: '1em'}}>{presetButtons}</div>
<Header as='h3'>People</Header>
<Grid>
{CATEGORY_META.map(meta =>
<Grid.Col key={meta.key} span={{base: 12, xs: 6}}>{countInput(meta)}</Grid.Col>)}
</Grid>
<Header as='h3' style={{marginTop: '1em'}}>
Daily Use ({rateUnit} per person) <InfoPopup content={DEMAND_INFO}/>
</Header>
<Grid>
{CATEGORY_META.map(meta =>
<Grid.Col key={meta.key} span={{base: 12, xs: 6}}>{rateInput(meta)}</Grid.Col>)}
</Grid>
<Header as='h3' style={{marginTop: '1em'}}>Additional daily demand</Header>
<div style={{maxWidth: '320px'}}>
<SwatchInput hex='#5f686a' label={`Extra ${rateUnit}`} value={extra} min={0} step={0.1} name="extra"
onChange={value => setExtra(clampNonNegative(value))}/>
<p style={{fontSize: '0.85em', opacity: 0.7, marginTop: '0.25em'}}>
Pets, livestock, guests, sick household members, or anything else not covered above.
</p>
</div>
<Header as='h3' style={{marginTop: '1em'}}>How long?</Header>
<div style={{padding: '0 0.5em'}}>
<input type='range' min={0} max={DURATION_STOPS.length - 1} step={1}
value={durationStop} aria-label='Duration'
onChange={e => setDurationIndex(Number(e.target.value))}
style={{width: '100%'}}/>
<Header as='h2' style={{marginTop: '0.25em', textAlign: 'center'}}>
{formatDuration(days)}
</Header>
</div>
<Panel style={{marginTop: '1em'}}>
<Table>
<Table.Body>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Daily Use</Table.Cell>
<Table.Cell>{fmt(daily, `${volumeUnit}/day`)}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Total Water for {formatDuration(days)}</Table.Cell>
<Table.Cell>{fmt(total, volumeUnit)}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell style={{fontWeight: 600}}>Water Weight</Table.Cell>
<Table.Cell>{fmt(weight, weightUnit)}</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<Header as='h3'>Containers Needed</Header>
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Container</Table.HeaderCell>
<Table.HeaderCell>Capacity</Table.HeaderCell>
<Table.HeaderCell>Needed</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>{containerRows}</Table.Body>
</Table>
</Panel>
</div>;
}